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.setは、​​ content-disposition が でオーバーライドされることに注意してくださいres.download。基本的にはこれですべてres.downloadです。 content-disposition を設定してから を呼び出しますsendfile。)

于 2013-05-01T17:42:10.717 に答える