Java 單檔案下載及重新命名

來源:互聯網
上載者:User

標籤:目標   head   get   code   point   office   []   rom   ext   

 

代碼(僅供參考):

 1 /* 2 * 另存新檔 3 */ 4 @RequestMapping("/saveAs.do") 5 public @ResponseBody void saveAs(String filePath,String fileName){ 6  7 try { 8 File file=new File(filePath); 9 //設定檔案MIME類型 10 getResponse().setContentType(getMIMEType(file)); 11 //設定Content-Disposition 12 getResponse().setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8")); //此處可以重新命名13 //擷取目標檔案的絕對路徑 14 String fullFileName = getRealPath("/upload/"+filePath); 15 //System.out.println(fullFileName); 16 //讀取檔案 17 InputStream in = new FileInputStream(fullFileName); 18 //讀取目標檔案,通過response將目標檔案寫到用戶端19 OutputStream out = getResponse().getOutputStream(); 20 //寫檔案 21 int b; 22 while((b=in.read())!= -1) 23 { 24 out.write(b); 25 } 26 in.close(); 27 out.close(); 28 } catch (Exception e) {29 e.printStackTrace();30 }31 }32 33 /**34 * 根據檔案尾碼名獲得對應的MIME類型。35 * 36 * @param file37 */38 private String getMIMEType(File file) {39 String type = "*/*";40 String fName = file.getName();41 // 擷取尾碼名前的分隔字元"."在fName中的位置。42 int dotIndex = fName.lastIndexOf(".");43 if (dotIndex < 0) {44 return type;45 }46 /* 擷取檔案的尾碼名 */47 String end = fName.substring(dotIndex, fName.length()).toLowerCase();48 if (end == "")49 return type;50 // 在MIME和檔案類型的匹配表中找到對應的MIME類型。51 for (int i = 0; i < MIME_MapTable.length; i++) { 52 if (end.equals(MIME_MapTable[i][0]))53 type = MIME_MapTable[i][1];54 }55 return type;56 }57 58 59 private final String[][] MIME_MapTable = {60 // {尾碼名, MIME類型}61 { ".doc", "application/msword" },62 { ".docx",63 "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },64 { ".xls", "application/vnd.ms-excel" },65 { ".xlsx",66 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },67 { ".pdf", "application/pdf" },68 { ".ppt", "application/vnd.ms-powerpoint" },69 { ".pptx",70 "application/vnd.openxmlformats-officedocument.presentationml.presentation" },71 { ".txt", "text/plain" }, { ".wps", "application/vnd.ms-works" },72 { "", "*/*" } };73 74  

 

效果:

Chrome

360IE

 

Java 單檔案下載及重新命名

聯繫我們

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