weixin_50065521
天才小蟑螂
采纳率0%
2021-02-28 22:06

移动端下载图片时报 java.io.IOException: Broken pipe异常如何解决?

这是后端代码:

@RequestMapping("/download")
    public void download(String path, HttpServletResponse response) {
        if (path == null || path.equals("")) {
            throw new ParamDissatisfyException("参数不足!");
        }
        log.info("下载URL:{}", path);
        //过滤URL
        path = path.replaceAll("%3A", ":").replaceAll("%2F", "/")  //过滤URL 包含中文
                .replaceAll("%3F", "?").replaceAll("%3D", "=").replaceAll(
                        "%26", "&");
        path = path.substring(path.lastIndexOf(":") + 1);
        path = imageUploadPath + path.substring(path.indexOf("/"));
        log.info("确认资源URL:{}", path);
        //得到该文件
        File file = new File(path);
        if (!file.exists()) {
            throw new FileNotExistException("文件不存在");
        }
        //取得文件名。
        String filename = file.getName();
        try {
            //将响应的类型设置为图片
            response.setContentType("image/jpeg");
            response.addHeader("Content-Length", "" + file.length());
            response.setHeader("Content-Disposition", "attachment;filename=" +         URLEncoder.encode(filename, "UTF-8"));
            FileInputStream fileInputStream = new FileInputStream(file);
            OutputStream out = response.getOutputStream();
            int len = 0;
            byte[] by = new byte[1024 * 8];
            while ((len = fileInputStream.read(by)) > 0) {
                out.write(by, 0, len);
            }
            out.close();
            fileInputStream.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

这是前端代码:

let form = $("<form>");
    form.attr("style", "display:none");
    form.attr("id", "downForm");
    form.attr("method", "post");
    form.attr("action", action);
    let input = $("<input>");
    input.attr("type", "hidden");
    input.attr("name", "path");
    input.attr("value", url);

    $("body").append(form);
    form.append(input);
    form.submit();
    $("#downForm").remove();
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • weixin_50065521 天才小蟑螂 2月前

    Chrome浏览器倒不会有问题

    点赞 评论 复制链接分享