|
提供上传和下载页面的JSP文件 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <meta charset="UTF-8">
7 <title>Insert title here</title>
8 </head>
9 <body>
10 <h2>用户注册</h2>
11 <form action="register" enctype="multipart/form-data" method="post">
12 <table>
13 <tr>
14 <td>用户名:</td>
15 <td><input type="text" name="username"></td>
16 </tr>
17 <tr>
18 <td>请上传头像:</td>
19 <td><input type="file" name="image"></td>
20 </tr>
21 <tr>
22 <td><input type="submit" value="注册"></td>
23 </tr>
24 </table>
25 </form>
26
27 <script type="text/javascript">
28 function test() {
29 var filename = document.getElementById("filename");
30 alert(encodeURIComponent(filename));
31 }
32 </script>
33
34 <h3>文件下载</h3>
35 <a href="javascript:window.location.href='download?filename=' +
36 encodeURIComponent('${requestScope.filename }')">
37 ${requestScope.filename }
38 </a>
39 </body>
40 </html>
|
SpringMVC提供了一个ResponseEntity类型,使用它可以很方便定义返回的BodyBuilder、HttpHeaders、HttpStatus。
2 public String register(HttpServletRequest request, @ModelAttribute User user, Model model) throws IllegalStateException, IOException {
3 System.out.println(user.getUsername());
4 // 如果上传文件部位空,写入上传文件路径
5 if (!user.getImage().isEmpty()) {
6 // 上传路径
7 String path = request.getServletContext().getRealPath("/images");
8 // 上传文件名
9 String filename = user.getImage().getOriginalFilename();
10 File filepath = new File(path, filename);
11 // 判断路径是否存在,不存在就创建一个
12 if (!filepath.getParentFile().exists()) {
13 filepath.getParentFile().mkdirs();
14 }
15 // 将上传文件保存到一个目标文件中
16 user.getImage().transferTo(new File(path + File.separator + filename));
17 // 将文件名保存到model中
18 model.addAttribute("filename", filename);
19 System.out.println("文件上传路径:" + (path + File.separator + filename));
20 return "userInfo";
21 } else {
22 return "error";
23 }
24 }
25
26 @RequestMapping(value="/download")
27 public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename,
28 @RequestHeader("User-Agent") String userAgent) throws IOException {
29 // 下载文件的路径
30 String path = request.getServletContext().getRealPath("/images");
31 // 构建File
32 File file = new File(path + File.separator + filename);
33 // ok表示http请求中状态码200
34 BodyBuilder builder = ResponseEntity.ok();
35 // 内容长度
36 builder.contentLength(file.length());
37 // application/octet-stream 二进制数据流(最常见的文件下载)
38 builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
39 // 使用URLEncoding.decode对文件名进行解码
40 filename = URLEncoder.encode(filename, "UTF-8");
41 // 根据浏览器类型,决定处理方式
42 if (userAgent.indexOf("MSIE") > 0) {
43 builder.header("Content-Disposition", "attachment; filename=" + filename);
44 } else {
45 builder.header("Content-Disposition", "attacher; filename*=UTF-8''" + filename);
46 }
47 return builder.body(FileUtils.readFileToByteArray(file));
48 }
|
程序猿的技术大观园:www.javathinker.net
|
|