zoukankan      html  css  js  c++  java
  • 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>
        </>
      );
    };
    
    
  • 相关阅读:
    emWin 界面切换注意事项
    emWin 工程之汉字显示
    emWin 使用 GUIBuilder 放置标题 TEXT 注意
    【转】系统调用和驱动程序中相应函数的参数对应关系
    主机 & 虚拟机 & 开发板 相互通信
    电脑通过网口连接开发板
    【转】ARM交叉编译工具链
    【转】vi 写完文件保存时才发现是 readonly
    【转】ubuntu 12.04下如何开启 NFS 服务 & 设置
    安装完打开 eclipse 提示 JVM 版本较低
  • 原文地址:https://www.cnblogs.com/wattmelon/p/14281599.html
Copyright © 2011-2022 走看看