0

我不能只下载一个文件来响应 ajax 发布请求。

$(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')
})
4

1 回答 1

1

看起来好像您希望单击图像以触发下载对话框。如果是这种情况,请不要使用 Ajax。发送帖子并让浏览器处理对话框。作为点击的结果发布可以通过创建一个简单的表单来完成。

$("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.setcontent-disposition 将被覆盖res.download。基本上就是res.download这样;它设置 content-disposition 然后调用sendfile。)

于 2013-05-01T17:42:10.717 回答