【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

持之以恒
原文地址:https://www.cnblogs.com/zwqh/p/6259506.html