解决前后端传送文件名,出现乱码问题,URLEncoder

在这里插入图片描述
出现???.doc,无法完成下载,后端的文件名在传输过程中,编码出现了问题。

解决,采用后端java在响应头中的里设置文件名称(URLEncoder.encode),前端vue,var fileName = decodeURIComponent(fileNameUtf8),进行解码。

 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("作业下载失败!请重试!")
                });

            }

效果图:
在这里插入图片描述
人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站:
https://www.captainai.net/shuai

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

汪程序猿

就当请我吃顿饭

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

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

打赏作者

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

抵扣说明:

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

余额充值