參考資料:blob文件下載=>通過文件流下載文件(B站視頻:BV1Vt4y1v7ih)
- 后端
const express = require('express');
const app = express();
const path = require('path')
// 文件是test.pdf
const imgPath = path.join(__dirname,'public','test.pdf')
app.use(express.static(path.join(__dirname,'public')))
// 解決跨域
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "*");
next();
});
// 測試連接
app.get('/test', function(req, res) {
res.send({id:123, name: 456});
});
// 直接下載
app.get('/download',(req,res)=>{
res.download(imgPath)
})
// 在頁面展示
app.get('/sendFile',(req,res)=>{
res.sendFile(imgPath)
})
app.listen(2000)
- 前端
遇到的問題:返回的response是null
原因:在已有項目上繼續開發維護,原有項目定義了全局的requset過濾器,需要判斷一下請求文件的情況。
import React from 'react';
import { Button } from 'antd';
import 'antd/dist/antd.css';
import request from 'umi-request';
export default () => {
function download() {
request('http://localhost:2000/download', {
method: 'GET',
responseType: 'blob',
}).then(res => {
console.log(res)
const blob = new Blob([res]);
const objectURL = URL.createObjectURL(blob);
let btn = document.createElement('a');
btn.download = '文件名.pdf';
btn.href = objectURL;
btn.click();
URL.revokeObjectURL(objectURL);
btn = null;
});
}
function sendFile() {
request('http://localhost:2000/sendFile', {
method: 'GET',
responseType: 'blob',
}).then(result => {
console.log(result)
// 需要指定文件類型,谷歌瀏覽器不能打開xlsx、doc等等
var blob = new Blob([result], {
type: "application/pdf;chartset=UTF-8"
});
//新窗口打開
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.target = "_blank";
link.click();
})
}
return (
<>
<Button onClick={download}>下載</Button>
<Button onClick={sendFile}>預覽</Button>
</>
);
};