【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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值