VUE下载文件错误信息回显

VUE下载文件,正确则下载,错误则解析提示错误信息,比如文件不存在(需要后端配合,后端springboot写入到response)

VUE前端代码

axios({
                        method: 'get',
                        url:  window.location.origin + '/xxx/download?fileName=' + name+'&id='+id,
                        // responseType: 'blob',
                        responseType: 'arraybuffer',
                        changeOrigin: true,
                        // headers: {'Content-Type':'application/json; application/octet-stream'}
                    })
                      .then(res => {
                        let enc = new TextDecoder();//,默认转utf-8
                        let uint8_msg = new Uint8Array(res.data);
                        let response = enc.decode(uint8_msg);
                        if (response.includes('msg')) {
                            Message.error(JSON.parse(response).msg)
                            return true
                        }else{
                            Message({
                                message: '下载中...',
                                type: "warning",
                                duration: 3 * 1000
                            });
                            //默认是这个,如果后端没有返回则使用默认,返回了则使用后端返回文件名
                            let filename = name + '-service.zip'
                            let temp = res.headers["content-disposition"]
                            let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                            let matches = filenameRegex.exec(temp);
                            if (matches != null && matches[1]) {
                                filename = matches[1].replace(/['"]/g, '');
                            }
                            let blob = new Blob([res.data], {type: res.headers['content-type']});
                            const downloadUrl = window.URL.createObjectURL(blob);
                            const link = document.createElement('a');
                            link.href = downloadUrl;
                            link.setAttribute('download', filename); //any other extension
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link); //下载完成移除元素
                            window.URL.revokeObjectURL(downloadUrl); //释放blob对象
                            Message({
                                message: '下载完成',
                                type: "success",
                                duration: 3 * 1000
                            });
                            return true
                        }
                    })
                      .catch(function (error) {
                          Message({
                              message: '下载异常!',
                              type: "error",
                              duration: 3 * 1000
                          });
                          console.log('catch error',error)
                      })

springboot代码

//后端正确则写入response
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.setAttachmentResponseHeader(response, realFileName);
        FileUtils.writeBytes(filePath, response.getOutputStream());
        //FileUtils.setAttachmentResponseHeader方法
        	String percentEncodedFileName = percentEncode(realFileName);
        	StringBuilder contentDispositionValue = new StringBuilder();
contentDispositionValue.append("attachment;filename=").append(percentEncodedFileName).append(";").append(
                "filename*=").append("utf-8''").append(percentEncodedFileName);
        	response.setHeader("Content-disposition", contentDispositionValue.toString());
        //FileUtils.writeBytes方法
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }
        try (FileInputStream fis = new FileInputStream(file);) {
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        }
//若后端错误则返回错误情况:
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            Map<String, Object> m = new HashMap<>();
            m.put("msg", e.getMessage());
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                writer.write(JSONObject.toJSONString(m));
            } catch (IOException ex) {
                e.printStackTrace();
            } finally {
                if (writer != null) {
                    writer.close();
                }
            }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值