java根据网络url下载图片文件

public class CommonUtils {

    public static boolean validateUrl(String url){
        String regex = "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?";
        Pattern pattern = Pattern.compile(regex);
            return pattern.matcher(url).matches();
    }
}

    //文件下载相关代码
    @ApiOperation(value = "处理前端跨域下载文件的问题,通过传入的url,前端下载文件到本地")
    @RequestMapping(value = "/downloadFile", method = RequestMethod.POST)
    public void downloadImage(@RequestBody BaseServiceRequest<String> request, HttpServletResponse response) {
        BufferedInputStream bin = null;
        OutputStream out = null;
        try {
            String url = request.getRequest();

            if (!CommonUtils.validateUrl(url)) {
                log.error("url:{},该链接为非法url!", url);
            }
            String fileName = url.substring(url.lastIndexOf("/")).toLowerCase().substring(1);
            url = url.replaceAll("/", "\\/");


            if (url != null) {
                // 统一资源
                URL urlPath = new URL(url);
                // 连接类的父类,抽象类
                URLConnection urlConnection = urlPath.openConnection();
                // http的连接类
                HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                // 设定请求的方法,默认是GET
                httpURLConnection.setRequestMethod("GET");
                // 设置字符编码
                httpURLConnection.setRequestProperty("Charset", "UTF-8");
                httpURLConnection.setConnectTimeout(5 * 1000);
                httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
                httpURLConnection.connect();

                // 文件大小
                int fileLength = httpURLConnection.getContentLength();

//                response.reset();
//                response.setContentType("application/force-download");// 设置强制下载不打开
//                response.setContentType("application/octet-stream");// 根据个人需要,这个是下载文件的类型
//                response.setContentType("multipart/form-data");
                response.setHeader("Pragma", "No-cache");
                response.setHeader("Cache-Control", "No-cache");
                response.setDateHeader("Expires", 0);
                response.setContentType("image/jpeg");
                // 中文文件名必须转码为 ISO8859-1,否则为乱码
                String fileNameDown = new String(fileName.getBytes("utf-8"), "ISO8859-1");
                // 作为附件下载
                response.setHeader("Content-Disposition", "attachment;filename=" + fileNameDown);
                response.addHeader("Content-Length", fileLength + "");

                bin = new BufferedInputStream(httpURLConnection.getInputStream());

                out = response.getOutputStream();
                int size = 0;
                int len = 0;
                byte[] buf = new byte[1024 * 1024 * 1];
                while ((size = bin.read(buf)) != -1) {
                    len += size;
                    out.write(buf, 0, size);
                }
                out.flush();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (bin != null) {
                    bin.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

前端请求代码:

import request from '@/utils/request'

export function fetchDownloadFile(data) {
  return request({
    url: '/api/private/resources/downloadFile',
    method: 'post',
    data: {
      'request': data
    }
  })
}
 downloadFile2() {
      fetchDownloadFile(this.resourcesContent).then(response => {
        console.log('=============================download file')
        console.log(response)
      })
    },

BaseServiceRequest是后端封装的请求格式,前端代码是在vue中使用的js调用

猜你喜欢

转载自blog.csdn.net/u011662320/article/details/86079614