通过ajax表示下载文件 [英] express download file via ajax

查看:240
本文介绍了通过ajax表示下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法下载文件以响应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表示下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆