So, in my Sinatra project I create a .zip file with some songs and then I want do return that file as a response with send_file
helper. And when I try to download the file with React in front-end, it downloads something but it says that it is invalid format or damaged.
This is the code I have in Sinatra:
def download_songs(song_list)
time = Time.new
temp_dir_name = rand(100000..999999).to_s + time.strftime("%d%m%Y%H%M%S")
Dir.mkdir(temp_dir_name)
song_list.each { |song|
formatted_command = 'youtube-dl -o "' + __dir__.to_s + '/' + temp_dir_name + '/%(title)s.%(ext)s" -x --audio-format mp3 "ytsearch:' + song + '"'
system formatted_command
}
zipfile_name = "#{__dir__.to_s}/#{temp_dir_name}/YourSongs.zip"
folder_to_zip = "#{__dir__.to_s}/#{temp_dir_name}"
file_names = Dir.children(temp_dir_name)
Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
file_names.each do |filename|
zipfile.add(filename, File.join(folder_to_zip, filename))
end
end
file_to_send_to_front = "./" + temp_dir_name + "/YourSongs.zip"
send_file file_to_send_to_front, :filename => "YourSongs.zip", :type => 'application/octet-stream'
end
And I call that function in this piece of code:
post '/download' do
content_type :json
all_songs_to_download = params['songs'].split(',')
download_songs(all_songs_to_download)
end
And when it downloads it locally on the server. I can open it normaly, so I would say that Zip is not being created incorrectly, but that React is downloading it wrongly or send_file
is sending it in a wrong way. Btw I tried to send a normal README.md
file the same way and it worked fine.
And this is code in React I use to download the .zip file:
_downloadSongs = () => {
let data = new FormData();
data.append('songs', this.state.songs);
axios({
method: "POST",
url: 'http://localhost:4567/download',
data: data,
headers: {'Content-Type': 'multipart/form-data'}
}).then(res => {
fileDownload(res.data, 'YourSongs.zip');
}).catch(err => {
console.log(err)
})
}
NOTE: I am using js-file-download to download the file I recieve as response from Sinatra.
Have you tried setting the following in send_file
:
:type => 'application/zip',
:disposition => 'attachment'