简体   繁体   English

Express res.download()

[英]Express res.download()

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? 有任何想法吗?

我认为您遇到的问题是您使用的是HTTP POST而不是HTTP GET

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. 只需将文件名替换为您的文件名即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM