標籤:目標 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 單檔案下載及重新命名