导出图片并下载

135 篇文章 0 订阅
32 篇文章 1 订阅

作用

下载远程图片

代码

public static void download(HttpServletResponse response, String fileUrl, String fileName) {
        if (EmptyUtil.notEmpty(fileUrl)) {
            try {
                //把 文件字节长度给 byte[], 输入流读取到 byte[] 中
                byte[] buffer = getFileBytes(fileUrl);
                if (EmptyUtil.notEmpty(buffer)) {
                    //输出流
                    OutputStream os = null;
                    try {
                        String contentTypeValue = "application/octet-stream";
                        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                        // 设置响应头信息
                        response.setContentType(contentTypeValue);
                        //定义输出流
                        os = response.getOutputStream();
                        //把 输出流写入 字节byte[]中数据
                        os.write(buffer, 0, buffer.length);

                    } catch (IOException ex) {
                        ex.printStackTrace();
                    } finally {
                        if (os != null)
                            os.close();
                    }
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }

    public static byte[] getFileBytes(String fileUrl) {
        //文件全路径 :sysFile.getStorePath()
        File file = new File(fileUrl);
        if (!file.exists()) {
            return null;
        }
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fis.read(data);
            return data;
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值