问题描述
我无法下载文件以响应ajax发布请求.
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代码
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')
})
推荐答案
它似乎就像您希望单击图像来触发下载对话框一样.如果是这种情况,请不要使用Ajax.发送帖子,然后让浏览器处理对话框.点击产生的结果可以通过创建一个简单的表单来完成.
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();
});
(请注意,在您的示例中,内容处置的res.set
只会在res.download
中被覆盖.这基本上是所有res.download
所做的;它会设置内容处置,然后调用sendfile
. )
(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
.)
这篇关于通过ajax表示下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!