记一次下载excel模板踩的坑

前端

export function downloadFile(url, fileName, parameter) {
  return downFile(url, parameter).then((data) => {
    if (!data || data.size === 0) {
      Vue.prototype['$message'].warning('文件下载失败')
      return
    }
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(new Blob([data]), fileName)
    } else {
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) //下载完成移除元素
      window.URL.revokeObjectURL(url) //释放掉blob对象
    }
  })

后端

	 public void getMb(HttpServletResponse response) {
		 String filePath = this.getClass().getClassLoader().getResource("static/template/wmcgjc.xlsx").getPath();
		 File file = new File(filePath);
		 try (OutputStream os = response.getOutputStream();
			  BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
			  BufferedOutputStream bos = new BufferedOutputStream(os)) {

			 response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			 response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("wmcgjc.xlsx", "UTF-8"));

			 byte[] buff = new byte[2048];
			 int bytesRead;
			 while ((bytesRead = bis.read(buff)) != -1) {
				 bos.write(buff, 0, bytesRead);
			 }
		 } catch (Exception e) {
			 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			 try {
				 response.getWriter().write("模板下载失败: " + e.getMessage());
			 } catch (IOException ioException) {
				 ioException.printStackTrace();
			 }
		 }
	 }

看起来都没有什么问题,就是一直文件损坏,排查了一个多小时忽然想起来看了看target,果然!!! 打包的文件损坏了!!

在pom添加

     <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <nonFilteredFileExtensions>
                        <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
                        <nonFilteredFileExtension>woff</nonFilteredFileExtension>
                        <nonFilteredFileExtension>woff2</nonFilteredFileExtension>
                        <nonFilteredFileExtension>eot</nonFilteredFileExtension>
                        <nonFilteredFileExtension>ttf</nonFilteredFileExtension>
                        <nonFilteredFileExtension>svg</nonFilteredFileExtension>
                    </nonFilteredFileExtensions>
                </configuration>
            </plugin>

这样就不会压缩损坏了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

尹劭东

(❁´◡`❁)给口饭吃吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值