Solve the problem of garbled characters in the front-end and back-end transmission file names, URLEncoder

insert image description here
???.doc appears, the download cannot be completed, and the back-end file name is in the process of transmission, and there is a problem with the encoding.

To solve, use the back-end java to set the file name (URLEncoder.encode) in the response header, and the front-end vue, var fileName = decodeURIComponent(fileNameUtf8), to decode.

 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") );
    @GetMapping("/download/{id}")
    public void download(@PathVariable("id") int id,
                         HttpServletResponse response) {
    
    

        String fileRealPath = submitHomeworkService.queryById(id).getFileRealPath();
        String fileName = submitHomeworkService.queryById(id).getFileName();
        File file = new File(fileRealPath);
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
    
    
            //文件是否存在
            if (file.exists()) {
    
    
                response.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有
                //设置响应
                response.setContentType("application/octet-stream;charset=UTF-8");
                // 将响应头中的Content-Disposition暴露出来,不然前端获取不到
                response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
                // 在响应头中的Content-Disposition里设置文件名称
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") );
//                response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                os = response.getOutputStream();
                bis = new BufferedInputStream(new FileInputStream(file));
                while (bis.read(buffer) != -1) {
    
    
                    os.write(buffer);
                }
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            try {
    
    
                if (bis != null) {
    
    
                    bis.close();
                }
                if (os != null) {
    
    
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
    }
     saveFile(id) {
    
    
                // window.open(url);
                // window.open(url, '_blank');

                this.$axios.get('http://localhost:8888/file/download/' + id,
                    {
    
    responseType: 'blob'}
                ).then((res) => {
    
    
                    // console.log('文件下载成功');
                    const blob = new Blob([res.data]);
                    // 获取文件名称, res.headers['content-disposition']:  attachment;filename=???????.docx
                    const fileNameUtf8 = res.headers['content-disposition'].split(";")[1].split("filename=")[1];
                    //%E8%BD%AF%E4%BB%B6%E9%A1%B9%E7%9B%AE%E8%AE%A1%E5%88%92%E8%A1%A8.docx  解码后:软件项目计划表.docx
                    var fileName = decodeURIComponent(fileNameUtf8)
                    console.log("res:" + res.headers['content-disposition'])
                    console.log("fileName:" + fileName)
                    //对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
                    //IE10以上支持blob,但是依然不支持download
                    //支持a标签download的浏览器
                    const link = document.createElement('a');//创建a标签
                    link.download = fileName;//a标签添加属性
                    link.style.display = 'none';
                    link.href = URL.createObjectURL(blob);
                    document.body.appendChild(link);
                    link.click();//执行下载
                    URL.revokeObjectURL(link.href); //释放url
                    document.body.removeChild(link);//释放标签
                    this.$message.success("作业下载成功!")
                }).catch((res) => {
    
    
                    this.$message.error("作业下载失败!请重试!")
                });

            }

Effect picture:
insert image description here
artificial intelligence learning website, easy to understand, humorous, I can't help but share it with everyone. Click to jump to the website:
https://www.captainai.net/shuai

Guess you like

Origin blog.csdn.net/m0_61504367/article/details/129124707