React文件流使用umi-request下载与预览pdf / jpeg

参考资料:blob文件下载=>通过文件流下载文件(B站视频:BV1Vt4y1v7ih

  1. 后端
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)
  1. 前端

遇到的问题:返回的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>
    </>
  );
};

posted @ 2021-01-15 13:33  wattmelon  阅读(4829)  评论(0编辑  收藏  举报