Java如何從伺服器中下載圖片_java

來源:互聯網
上載者:User

本文執行個體為大家分享了Java伺服器中下載圖片的方法,供大家參考,具體內容如下

import java.io.IOException; import java.io.InputStream;  import java.io.OutputStream;  import java.net.URL; import java.net.URLConnection; import org.apache.commons.io.IOUtils;    /**   * 從伺服器中下載圖片   *   * @param fileName 圖片地址   * @param response   * @return   */  @RequestMapping(value = "/download")  public void downloadMedia(HttpServletResponse response, HttpServletRequest request) {    InputStream inputStream = null;    OutputStream outputStream = null;    try {      //處理中文亂碼      request.setCharacterEncoding("UTF-8");      String fileName = request.getParameter("fileName");      fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");      //處理瀏覽器安全色      response.setContentType("application/msexcel;charset=utf-8");//定義輸出類型      Enumeration enumeration = request.getHeaders("User-Agent");      String browserName = (String) enumeration.nextElement();      boolean isMSIE = browserName.contains("MSIE");      if (isMSIE) {        response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF8"));      } else {        response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));      }      //url地址如果存在空格,會導致報錯!  解決方案為:用+或者%20代替url參數中的空格。      fileName = fileName.replace(" ", "%20");      //圖片下載      URL url = new URL(fileName);      URLConnection conn = url.openConnection();      outputStream = response.getOutputStream();      inputStream = conn.getInputStream();      IOUtils.copy(inputStream, outputStream);    } catch (IOException e) {      System.err.println(e);    }finally {       IOUtils.closeQuietly(inputStream);       IOUtils.closeQuietly(outputStream);    }   }

以上就是本文的全部內容,希望對大家的學習有所協助。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.