java 网络资源下载

比如文件上传在OSS系统上面,那么我怎么让客户端下载到本地?
Services实现层:

attachment绝对路径,比如:https://imgsrc.baidu.com/baike/pic/item/dcc451da81cb39db5aacb0c8dc160924aa1830c4.jpg
public void fileDownload(HttpServletRequest request, HttpServletResponse response, String attachment) {
        // 获取上下文对象
        ServletContext servletContext = request.getSession().getServletContext();
        // 获取文件资源的路径
        String path = attachment;//servletContext.getRealPath(Constants.REPORT_REPORTFILEPATH);
        log.debug(path);

        URL url = null;
        InputStream openStream = null;
        try (OutputStream fos = response.getOutputStream();) {
            url = new URL(attachment);
            openStream = url.openStream();
            String mimeType = servletContext.getMimeType(attachment);
            if (mimeType == null) {
                mimeType = "application/octet-stream";
            }
            response.setContentType(mimeType);
            String headerkey = "Content-Disposition";
            String fileName = attachment.substring(attachment.lastIndexOf("/") + 1);
            String headerValue = String.format("attachment;filename=\"%s\"", fileName);
            response.setHeader(headerkey, headerValue);

            byte buff[] = new byte[BUFF_SIZE];
            int flag = -1;
            while ((flag = openStream.read(buff)) != -1) {
                fos.write(buff, 0, flag);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ProjectDetailServiceImpl fileDownload() have an exception {} = ", e);
        } finally {
            try {
                if (openStream != null) {
                    openStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值