前言:这篇文件下载的后台代码太繁琐,建议参考https://www.cnblogs.com/zwh0910/p/13745947.html

前端:

  1.  <el-button
    type="primary"
    icon="el-icon-download"
    @click="downloadTemplate('药品清单-模板.xlsx')">下载模板</el-button>

在main.js中:

  1. import fileDownload from 'js-file-download'

    Vue.prototype.downloadTemplate = function (templateName) {
    const fileEntity = {
    fileName: templateName,
    filePath: "D:\\prism\\svn\\drug-question\\drugques-pc\\src\\template\\"+templateName,
    downloadChannel: 'DIR'
    }
    medicineListApi.ptsFileDownload(fileEntity).then(response => {
    fileDownload(response.data, templateName)
    }).catch(error => {
    console.log(error)
    })
    }

在package.json中添加依赖版本

  1. "dependencies": {
  2. "@aximario/json-tree": "^2.1.0",
  3. "axios": "^0.19.0",
  4. "core-js": "^2.6.5",
  5. "echarts": "^4.2.1",
  6. "element-ui": "^2.13.2",
  7. "js-file-download": "^0.4.4",
  8. },

如果是下载本地的文件,则应写详细的路径:D:\prism\svn\drug-question\drugques-pc\src\template

在medicineList.js中

  1. const baseUrl = "/medicineList"
  1. ptsFileDownload(query) {
  2. return request({
  3. url: baseUrl +'/fileDownload',
  4. method: 'post',
  5. data: query,
  6. responseType: 'arraybuffer'
  7. })
  8. },

后台代码:

controller:

  1. @RequestMapping(value = "/fileDownload", method = { RequestMethod.POST, RequestMethod.GET })
    public String fileDownload(@RequestBody(required=true) PtsFileEntity fileEntity, HttpServletResponse response) throws Exception {
    medicineListService.fileDownload(fileEntity, response);
    return null;
    }

service接口

  1. public interface MedicineListService extends IService<DrugData> {
      void fileDownload(PtsFileEntity fileEntity, HttpServletResponse response) throws Exception;
  2. }

service实现类

  1.  
  1. @Override
    public void fileDownload(PtsFileEntity fileEntity, HttpServletResponse response) throws Exception {
    String fileName = fileEntity.getFileName();
    if (null == fileName || ("").equals(fileName.trim())) {
    logger.error("No FileName Found.");
    throw new Exception("No FileName Found.");
    }
    String downloadChannel = fileEntity.getDownloadChannel();
    if (null == downloadChannel || ("").equals(downloadChannel.trim())) {
    logger.error("Need to identity download channel.");
    throw new Exception("Need to identity download channel.");
    }
    if (CHANNEL_DIR.equalsIgnoreCase(downloadChannel)) {
    this.downloadFromDir(fileEntity, response);
    } else if (CHANNEL_URL.equalsIgnoreCase(downloadChannel)) {
    this.downloadFromUrl(fileEntity, response);
    }
    }
  1. /**
    * 从URL地址下载
    *
    * @param fileEntity
    * @param response
    * @throws Exception
    */
    private void downloadFromUrl(PtsFileEntity fileEntity, HttpServletResponse response) throws Exception {
    String filePath = fileEntity.getFilePath();
    String serverFilePath = fileEntity.getServerFilePath();
    if ((null == filePath || ("").equals(filePath.trim())) && (null == serverFilePath || ("").equals(serverFilePath.trim()))) {
    logger.error("No FilePath Found.");
    throw new Exception("No FilePath Found.");
    }
    String realFilePath = (null == filePath || ("").equals(filePath.trim())) ? serverFilePath : filePath;
    logger.info("Begin download file from Url: " + realFilePath);

    try {
    URL url = new URL(realFilePath);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    //设置超时间为3秒
    conn.setConnectTimeout(3 * 1000);
    //防止屏蔽程序抓取而返回403错误
    conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

    //得到输入流
    InputStream inputStream = conn.getInputStream();
    //获取自己数组
    byte[] srcBytes = readInputStream(inputStream);
    this.download(fileEntity, response);
    } catch (IOException e) {
    e.printStackTrace();
    throw new Exception(e);
    }
    }
    /**
    * 从输入流中获取字节数组
    *
    * @param inputStream
    * @return
    * @throws IOException
    */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
    byte[] buffer = new byte[1024];
    int len = 0;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while ((len = inputStream.read(buffer)) != -1) {
    bos.write(buffer, 0, len);
    }
    bos.close();
    return bos.toByteArray();
    }

    /**
    * 创建临时文件
    *
    * @param fileEntity
    * @param srcBytes
    */
    public void downloadFromDir(PtsFileEntity fileEntity, HttpServletResponse response) throws Exception {
    String filePath = fileEntity.getFilePath();
    String serverFilePath = fileEntity.getServerFilePath();
    if ((null == filePath || ("").equals(filePath.trim())) && (null == serverFilePath || ("").equals(serverFilePath.trim()))) {
    logger.error("No FilePath Found.");
    throw new Exception("No FilePath Found.");
    }
    String realFilePath = (null == filePath || ("").equals(filePath.trim())) ? serverFilePath : filePath;
    logger.info("Begin download file from Directory: " + realFilePath);
    fileEntity.setRealFilePath(realFilePath);
    try {
    // 以流的形式下载文件。
    InputStream fis;
    fis = new BufferedInputStream(new FileInputStream(realFilePath));
    byte[] srcBytes = new byte[fis.available()];
    fis.read(srcBytes);
    fis.close();
    this.download(fileEntity, response);
    } catch (IOException ex) {
    ex.printStackTrace();
    throw new Exception(ex);
    }
    }

    /**
    * 拼接response header 并已流的形式下载文件
    *
    * @param fileEntity
    * @param response
    * @throws Exception
    */
    public void download(PtsFileEntity fileEntity, HttpServletResponse response) throws Exception {
    String fileName = fileEntity.getFileName();
    String realFilePath = fileEntity.getRealFilePath();
    File file = new File(realFilePath);

    try {
    // 以流的形式下载文件。
    InputStream fis;
    fis = new BufferedInputStream(new FileInputStream(realFilePath));
    byte[] srcBytes = new byte[fis.available()];
    fis.read(srcBytes);
    fis.close();

    // 清空response
    response.reset();
    // 设置response的Header
    response.setHeader("Content-type", "text/html;charset=UTF-8");
    response.setCharacterEncoding("utf-8");//设置编码集,文件名不会发生中文乱码

    response.setContentType("application/force-download");//
    response.setHeader("content-type", "application/octet-stream");
    response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes(), "utf-8"));// 设置文件名
    response.addHeader("Content-Length", "" + file.length());
    response.setHeader("Access-Control-Allow-Origin", "*");
    OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
    toClient.write(srcBytes);
    toClient.flush();
    toClient.close();
    } catch (IOException ex) {
    throw new Exception(ex);
    }
    }

如果报错:The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'

解决:将request.js中的withCredentials由true改为false

  1. const service = axios.create({
  2. baseURL: "http://localhost:8080/drugques",
  3. withCredentials: false,
  4. timeout: 150000
  5. });

文件下载:报错The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'的更多相关文章

  1. 微信小程序WebSocket报错:Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received

    Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was ...

  2. python webdriver 报错WebDriverException: Message: can't access dead object的原因(pycharm中)

    PyCharm中运行firefox webdriver访问邮箱添加通讯录的时候报错-WebDriverException: Message: can't access dead object 调了半天 ...

  3. 【Mac 10.13.0】安装 libimobiledevice,提示报错:warning: unable to access '/Users/lucky/.config/git/attributes': Permission denied解决方案

    打开终端,执行命令: 1.sudo chown -R XXX /usr/local  (XXX表示当前用户名) 2.ruby -e "$(curl -fsSL https://raw.git ...

  4. mysql忘记root密码或报错:ERROR 1044 (42000): Access denied for user ”@’localhost’ to database ‘xx‘

    有的时候忘记了root密码或其他用户的密码,登录的时候报错:ERROR 1044 (42000): Access denied for user ”@’localhost’ to database ' ...

  5. Access control allow origin 简单请求和复杂请求

    原文地址:http://blog.csdn.net/wangjun5159/article/details/49096445 错误信息: XMLHttpRequest cannot load http ...

  6. Ubuntu下MySQL报错:ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

    在Ubuntu下 想要登录mysql数据库 root@JD:~# mysql -uroot -p 报错 ERROR 1045 (28000): Access denied for user 'root ...

  7. 【问题与解决】Mac OS通过 npm 安装 React Native 报错(checkPermissions Missing write access to /usr/local/lib/node_modules)

    报错情况: 当Mac OS通过 npm 安装 React Native 报错,警告文字为:checkPermissions Missing write access to /usr/local/lib ...

  8. 报错:PermissionError: [WinError 5] Access is denied: 'C:\\Program Files\\Anaconda3\\Lib\\site-packages\\pywebhdfs'

    Outline 在本(Windows系统)地往 “PAI”(hdfs)上上传数据时,需要安装pywebhdfs包,然后就报错了: 报错信息: PermissionError: [WinError 5] ...

  9. CM使用MySQL数据库预处理scm_prepare_database.sh执行报错:java.sql.SQLException: Access denied for user 'scm'@'hadoop101.com' (using password: YES)

    1.报错提示: [root@hadoop101 ~]# /opt/module/cm/cm-/share/cmf/schema/scm_prepare_database.sh mysql cm -hh ...

随机推荐

  1. UML——宏观总结

    今天果断开始UML的学习,要不就要被12期赶超了.努力学习的效率 一.宏观导图把控 导图概要说明:RUP这块儿的内容相当于软件工程已经学过了,只不过这里换了个名词而已.面向对象,已经不再陌生,vb中早 ...

  2. 一文弄懂-BIO,NIO,AIO

    目录 一文弄懂-BIO,NIO,AIO 1. BIO: 同步阻塞IO模型 2. NIO: 同步非阻塞IO模型(多路复用) 3.Epoll函数详解 4.Redis线程模型 5. AIO: 异步非阻塞IO ...

  3. P4254 [JSOI2008]Blue Mary开公司 (李超树)

    题意:插入一些一次函数线段 每次询问在x = x0处这些线段的最大值 题解:李超树模版题 维护优势线段 注意这题的输入是x=1时的b #include <iostream> #includ ...

  4. Codeforces Round #604 (Div. 2) C. Beautiful Regional Contest(贪心)

    题目链接:https://codeforces.com/contest/1265/problem/C 题意 从大到小给出 $n$ 只队伍的过题数,要颁发 $g$ 枚金牌,$s$ 枚银牌,$b$ 枚铜牌 ...

  5. 【poj 2478】Farey Sequence(数论--欧拉函数 找规律求前缀和)

    题意:定义 Fn 序列表示一串 <1 的分数,分数为最简分数,且分母 ≤n .问该序列的个数.(2≤N≤10^6) 解法:先暴力找规律(代码见屏蔽处),发现 Fn 序列的个数就是 Φ(1)~Φ( ...

  6. F - Count the Colors(线段树)

    Painting some colored segments on a line, some previously painted segments may be covered by some th ...

  7. 2020 ICPC Asia Taipei-Hsinchu Regional Problem B Make Numbers (dfs搜索)

    题意:给你四个数字,你可以用这四个数字凑出四个1位数,一个2位数和两个1位数,或一个3位数和一个1位数,你可以用你凑出的数字进行\(+,-,x\)运算(所有运算符号至少出现一次),问你一共能得到多少个 ...

  8. k8s二进制部署 - 总结

    镜像仓库: 安装软件:docker.docker-compose.harbor.nginx 1.下载cfssl.cfssljson.cfssl-certinfo,增加执行权限并放在PATH环境变量路径 ...

  9. Redis 的缓存淘汰机制(Eviction)

    本文从源码层面分析了 redis 的缓存淘汰机制,并在文章末尾描述使用 Java 实现的思路,以供参考. 相关配置 为了适配用作缓存的场景,redis 支持缓存淘汰(eviction)并提供相应的了配 ...

  10. 牛客网多校第4场 D Another Distinct Values 【构造】

    题目:戳这里 题意,n*n的矩阵,只能填-1,0,1,问能不能使该矩阵的任意行和列的和都不想等. 解题思路:戳这里 可以说是一目了然了 附ac代码: 1 #include<iostream> ...