【Java】Java 單文件下載及重命名


 

代碼(僅供參考):

 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 file
37 */
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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM