簡體   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