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

移动端下载图片时报 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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)