Express res.download()

元气小坏坏 提交于 2020-08-05 09:29:48

问题


I don't know why it's happening, but it's really annoying. I expected the file to be downloaded according to the express docs. I have the next code:

  //in react (App.js)
  download = () => {
    const { images, target } = this.state;
    const filename = images.find(img => img.id === target).filename;
    fetch('http://localhost:3001/download', {
      method: 'post',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({filename})
    })
  }
  //in express (server.js)
  app.post('/download', (req, res) => {
    var file = '../public/images/' + req.body.filename;
    res.download(file, req.body.filename);
  });

The folder structure:

  -server
    |-server.js
  -public
    |-images
      |-a.jpg
      |-b.jpg
  -src
    |-App.js

Nothing's happening, errors not shown. Any ideas?


回答1:


I think the issue you have is that you're using an HTTP POST instead of HTTP GET




回答2:


It was a challenge, but this worked for me.

let express = require('express'),
path = require('path'),
port = process.env.PORT || process.argv[2] || 8080,
app = express();

app.get('/', (req, res)=>{

res.send('<a href="/download">Download</a>');

});

app.get('/download', (req, res)=>{

res.download(path.join(__dirname, 'views/files.pug'), (err)=>{

    console.log(err);

});
console.log('Your file has been downloaded!')
});

app.listen(port, ()=>{

console.log('res is up on port: ' + port);

});
``

Just replace the file names with yours.



来源:https://stackoverflow.com/questions/52391627/express-res-download

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!