4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ajaxでファイルダウンロードをしたかった

Posted at

やりたいこと

フロントからAjaxでExpressサーバーにアクセスして、ファイルをダウンロードしたい!

できたコード

サーバーではバイナリを返して、フロントのJSでBlob作って、ObjectURL作って……みたいなことをしたのですが、うまく行かず。

結局以下の様なコードになりました。もうちょっとどうにかならないかね。。

(全コードはこちらから)

front.js
dom.addEventListener('click', (e) => {
  e.preventDefault();

  var xhr = new XMLHttpRequest();
  xhr.open('get', '/file');
  xhr.onreadystatechange = () => {
    if(xhr.readyState !== 4 || xhr.status < 200 || xhr.status >= 400) return;

    var res = JSON.parse(xhr.responseText);
    var a = document.createElement('a');
    a.href = 'data:image/jpeg;base64,' + res['base64'];
    a.download = 'Image.jpg';
    document.body.appendChild(a);
    a.click();
    a.parentNode.removeChild(a);
  };
  xhr.send(null);
});
server.js
router.get('/file', function(req, res, next) {
  const rs = fs.createReadStream(path.join(__dirname, '../public/images/image.jpg'));
  let data = [];
  rs.on('data', (c) => {
    data.push(c);
  });
  rs.on('end', () => {
    const buf = Buffer.concat(data);
    res.send({'base64': buf.toString('base64')});
  });
});
4
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?