繁体   English   中英

发送请求以返回下载文件

[英]Post request that returns a download file

我正在向我的服务器发送数据,根据请求创建一个pdf文件,这是正常创建但我不能将文件发送回客户端。 我使用React提交表单

handleSubmit(event) {
event.preventDefault();
var body = {
  id: this.state.id,
  text: this.state.text
}
fetch('http://localhost:5000/pdf', {
            method: 'POST',
            body: JSON.stringify(body),
            headers: {
                'Content-Type': 'application/json'
            },
        }).then(function(file) {
          window.open(file.url);
        });
}

它打开http:// localhost:5000 / pdf ,但由于我没有GET路由,所以没有任何内容可供下载。 这是我的POST路线

router.post('/pdf', async function(req, res) {
  var makePdf = require('./file-create/pdf.js');
  makePdf(req, res);
});

并且文件以pdfDoc.pipe(res);形式返回pdfDoc.pipe(res);

我不能使用GET路由,因为我无法以这种方式发送数据,如何将此文件发送到客户端?

当您使用window.open时,您正在调用GET请求。 这将在带有URL的新选项卡中打开URL。 当您将其从GET更改为POST时,这将不起作用。

要解决此问题,您可以使用downloadjshttps://www.npmjs.com/package/downloadjs )来下载从服务器返回的blob。

我在下面提供了一些示例代码。 这包括带有获取请求的index.html文件和用于返回简单pdf的server.js。

的index.html

 var body = { id: 1, text: 'hello world', }; fetch('/download', { method: 'POST', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' }, }).then(function(resp) { return resp.blob(); }).then(function(blob) { return download(blob, "CUSTOM_NAME.pdf"); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/downloadjs/1.4.8/download.min.js"></script> 

server.js

 var express = require('express'); var app = express(); app.post('/download', function(req, res){ res.download('./make-file/whatever.pdf'); }); app.listen(3000); 

暂无
暂无

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

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