下载远程图片并返回给前端

1.测试接口

    @GetMapping("test")
    private void test(HttpServletRequest request, HttpServletResponse response){
        String fileName = "94e497d0ad37b6087de56e068fa034c6.xlsx";
        String filePath = "https://www.baidu.com/94e497d0ad37b6087de56e068fa034c6.xlsx";
        FileUtils.download(response, filePath, fileName); // 下载操作
    }

2.实现:FileUtils.java

public static boolean download(HttpServletResponse response, String filePath, String fileName) {
        URL url = null;
        URLConnection con = null;
        InputStream is = null;
        OutputStream os = null;
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("content-disposition", "attachment;filename=" + fileName);
        try {
            url = new URL(filePath);
            con = url.openConnection();
            con.setConnectTimeout(5 * 1000);
            is = con.getInputStream();
            // 开始读取
            int len;
            byte[] bs = new byte[1024];
            os = response.getOutputStream();
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    os.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

 

上一篇:OpenCV.图形绘制.箭头


下一篇:abd remove