zoukankan      html  css  js  c++  java
  • 下载远程图片并返回给前端

    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;
        }
  • 相关阅读:
    html 时间区间选择功能
    Django 【settings】数据库设置
    Django forms 定制form字段
    避免js全局变量污染的方法
    js获取路由
    采用遍历的方法获取字符串a在字符串b中的位置
    vue 学习笔记
    Promise
    js常用JSON数据操作
    js 数组遍历方式
  • 原文地址:https://www.cnblogs.com/XueTing/p/15430324.html
Copyright © 2011-2022 走看看