zoukankan      html  css  js  c++  java
  • 通过url从图片服务器下载图片到浏览器(图片下载)下载图片而不是打开图片

    一、需求:平时写图片下载功能,只需要前台页面写download标签就可以实现图片的下载,本次项目遇到的问题是,由于搭建了图片服务器,请求图片URL的时候获取不到请求头,浏览器无法识别图片是文件,导致点击下载,浏览器会打开图片

    二、解决:既然浏览器获取不到请求头,考虑到的最简单的解决方式是通过后台下载,向图片服务器发送请求头

         考虑到下载图片使用频繁,所以把下载图片封装为通用方法,代码如下:

         实现步骤:1.前台向后台发送图片url

              2.通过url获取图片流

              3.设置输出头

              4.把图片输出到浏览器(不是写死图片地址)

            

         

     1 /**
     2      * 图片下载
     3      * @param fileUrl
     4      * @param response
     5      */
     6     @ApiOperation(value = "|uploadQianURL|图片下载")
     7     @GetMapping("/uploadQianURL")
     8     public void  uploadQianURL(String fileUrl,HttpServletResponse response) {
     9 
    10         fileUrl = fileUrl.replace("\", "/");
    11         //获取文件名,文件名实际上在URL中可以找到
    12         String[] strs=fileUrl.split("/");
    13         String fileName = strs[strs.length - 1].toString();
    14         try {
    15             URL url = new URL(fileUrl);/*将网络资源地址传给,即赋值给url*/
    16             /*此为联系获得网络资源的固定格式用法,以便后面的in变量获得url截取网络资源的输入流*/
    17             HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    18             DataInputStream in = new DataInputStream(connection.getInputStream());
    19             ServletOutputStream out=response.getOutputStream();
    20             response.setContentType("multipart/form-data");
    21             //获取当前超链接中文件的名字
    22             response.addHeader("Content-Disposition","attachment; filename="+ new String(fileName.getBytes("GB2312"), "ISO8859-1"));
    23 
    24             ByteArrayOutputStream output = new ByteArrayOutputStream();
    25 
    26             byte[] buffer = new byte[1024];
    27             int length;
    28 
    29             while ((length = in.read(buffer)) > 0) {
    30                 output.write(buffer, 0, length);
    31             }
    32             byte[] context=output.toByteArray();
    33             out.write(output.toByteArray());
    34             in.close();
    35             out.close();
    36 
    37             connection.disconnect();
    38             
    39 
    40 
    41         } catch (Exception e) {
    42 
    43 
    44         }
    45     }
  • 相关阅读:
    任务08——第一次半月学习总结
    任务5
    任务4
    任务3
    任务2
    mission 01
    HTML-CSS-JS Prettify报错Node.js was not found
    **1279
    UVa 10735
    UVa 1515
  • 原文地址:https://www.cnblogs.com/zHpx/p/9067657.html
Copyright © 2011-2022 走看看