java下載網路檔案並重新命名

來源:互聯網
上載者:User

檔案下載,通過<a href="url">也是可以的,但是這樣直接下載,一般檔案名稱就是伺服器端的沒有任何意義的檔案名稱。

今天自己用到了另外一種,先說需求:1.檔案伺服器與系統沒有在同一伺服器,所以需要使用網路地址來進行下載;

2.上傳時為了避免檔案重名,使用uuid來產生了檔案名稱,真實的檔案名稱存與資料庫中;

3.所有的檔案都只能下載,不可直接在瀏覽器上開啟。

根據代碼來分析:這裡使用的springmvc

[java]  view plain  copy  print ? @RequestMapping("/download")       public String downloadAmachment(String downloadUrl, String realFileName, HttpServletRequest request,               HttpServletResponse response) {           response.setContentType("text/html;charset=UTF-8");           try {               request.setCharacterEncoding("UTF-8");                  BufferedInputStream bis = null;               BufferedOutputStream bos = null;               //此處使用的設定檔裡面取出的檔案伺服器位址,拼湊成完整的檔案伺服器上的檔案路徑                           //寫demo時,可以直接寫成http://xxx/xx/xx.txt.這種形式                           String downLoadPath = ConfigHelper.getString("img.server.url") + downloadUrl;                  response.setContentType("application/octet-stream");               response.reset();//清除response中的緩衝               //根據網路檔案地址建立URL                           URL url = new URL(downLoadPath);                           //擷取此路徑的串連                           URLConnection conn = url.openConnection();                                          Long fileLength = conn.getContentLengthLong();//擷取檔案大小               //設定reponse回應標頭,真實檔案名稱重新命名,就是在這裡設定,設定編碼                           response.setHeader("Content-disposition",                       "attachment; filename=" + new String(realFileName.getBytes("utf-8"), "ISO8859-1"));               response.setHeader("Content-Length", String.valueOf(fileLength));                  bis = new BufferedInputStream(conn.getInputStream());//構造讀取流               bos = new BufferedOutputStream(response.getOutputStream());//構造輸出資料流               byte[] buff = new byte[1024];               int bytesRead;               //每次讀取緩衝大小的流,寫到輸出資料流                           while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {                   bos.write(buff, 0, bytesRead);               }               response.flushBuffer();//將所有的讀取的流返回給用戶端               bis.close();               bos.close();              } catch (IOException e) {               LOG.error(e.getMessage(), e);               return ErrorPages._500;           }           return

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.