Springboot_文件下载功能(前端后端)

遇到的问题:

  • 文件下载后文件一直被破坏,无法正常打开
  • 文件名乱码,如图

刚开始一直在纠结,是不是后端没有写对,然后导致下载不能使用

后来搜索了一些资料,发现后端没什么问题

然后就开始找到其他项目对比下载功能

哈哈哈哈哈哈哈

不会也只能靠这个方法去找问题了,就是有点笨,但总归找到了问题所在

下载功能后端代码

java 复制代码
    @GetMapping("/annex")
    public void downloadAnnex(ProcessFindReqVo processFindReqVo, HttpServletResponse response) throws IOException, HttpMediaTypeNotAcceptableException {
        String filePath = "文件路径"; // 指定文件路径
        if (StringUtils.isBlank(filePath)) {
            return;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            return;
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream;charset=UTF-8");
        String fileName = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buffer = new byte[(int)file.length()];
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(file);
            os = response.getOutputStream();
            int i = -1;
            while ((i = fis.read(buffer)) != -1) {
                os.write(buffer, 0, i);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

下载功能前端代码

js 复制代码
export async function downloadAnnex(data){
    const res = await axios.get(`/scm/web/monthly/download/annex?id=`+data, {
        responseType: 'blob'
      })
    const content = res.data
    const blob = new Blob([content], { type: 'application/octet-stream' })
    const contentDispositionHeader = res.headers['content-disposition'];
    const fileName = contentDispositionHeader.split(';')
            .map(item => item.trim())
            .find(item => item.startsWith('filename='))
            .substr('filename='.length);
    let decodeName = decodeURI(fileName);
    if ('download' in document.createElement('a')) { // 非IE下载
        const elink = document.createElement('a')
        elink.download = decodeName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
    } else { // IE10+下载
        navigator.msSaveBlob(blob, decodeName)
    }
}
  • 说回刚开始的问题,下载时文件始终提示被破坏的原因:
    export async function downloadAnnex(data){这里应该使用async关键字
    const res = await axios.get请求时也应该使用await关键字,这样就可以使文件顺利下载,至于为什么还没有深究。。。(想以后研究,不知道以后还能不能想起来了😅)
  • 文件名始终乱码,就使用decodeURI(fileName);进行解码,之后就可以正确的展示中文字符了,前提时后端传输时已经设置了UTF-8的编码
相关推荐
Rain的Java大神之路4 小时前
如何快速上传10G文件
java·spring boot·redis·后端·mysql·spring cloud·面试
百万蹄蹄向前冲5 小时前
风扇转了一晚上MVP专家团翻车事故
前端·人工智能
默_笙5 小时前
🏛 给 AI 配一间办公室:Harness Engineering 六大模块与它的实现
前端·javascript
linux_cfan6 小时前
videojs v10 源代码系列解读:14 · 谓词守卫:在运行时安全地调用能力
前端·javascript·音视频
kyriewen6 小时前
我扒了 10,221 条 JD:腾讯技术岗 75% 在要 AI
前端·人工智能·ai编程
郑州光合科技余经理7 小时前
同城外卖小程序开发:下单成功后,后台导出能不能对上用户端状态
开发语言·前端·git·后端·uni-app·php·ai编程
+VX:Fegn08958 小时前
计算机毕业设计|基于springboot + vue旅游管理系统(源码+数据库+文档)
java·开发语言·vue.js·spring boot·课程设计
IT_陈寒8 小时前
Vue的响应式让我熬到凌晨三点,原来漏了这个小细节
前端·人工智能·后端
需要8268 小时前
MySQL 索引 B+ 树与“查询为什么变慢了
java·spring boot·spring·spring cloud·tomcat
一 乐8 小时前
二手交易平台|基于springboot + vue二手交易平台(源码+数据库+文档)
java·数据库·vue.js·spring boot·小程序