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

移动端下载图片时报 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条回答 默认 最新

  • 天才小蟑螂 2021-02-28 22:08
    关注

    Chrome浏览器倒不会有问题

    评论

报告相同问题?

悬赏问题

  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决