Reputation: 1036
I cant just download a file in response to ajax post request.
$(function(){
$('img.download').click(function() {
var image_path = $(this).attr('class').split(" ")[1]
$.ajax({url:'/download',type:'POST',data:{image_path:image_path}})
})
})
Node.js code
app.post('/download',function(req,res){
//var image_path = req.body.image_path
//var filename = 'new.png'
res.set({
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment;filename=\"new.png\"'
})
//res.set('Content-type', 'image/png')
//var filestream = fs.createReadStream('public/uploads/new.png')
//filestream.pipe(res)
res.download('public/uploads/new.png')
})
Upvotes: 0
Views: 2467
Reputation: 34072
It appears as though you want the image click to trigger a download dialog. If this is the case, don't use Ajax. Send the post and let the browser handle the dialog. Posting as a result of a click can be accomplished by creating a simple form.
$("img.download").click(function () {
var image_path = $(this).attr('class').split(" ")[1];
var form = $('<form>', {action: '/download', method: 'POST'});
form.append($('<input>', {name: 'image_path', value: image_path}));
form.submit();
});
(Note that in your sample, res.set
of the content-disposition is just going to be overridden in res.download
. That's essentially all res.download
does; it sets the content-disposition and then calls sendfile
.)
Upvotes: 1