您的位置:首页 > 编程语言 > Java开发

SpringMVC框架(四)文件的上传下载,上下文路径

2017-10-11 09:37 351 查看
文件目录:



SpringMVC配置文件:

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4     xmlns:mvc="http://www.springframework.org/schema/mvc"
5     xmlns:context="http://www.springframework.org/schema/context"
6     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 7         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
9
10     <!-- 配置扫描器 -->
11     <context:component-scan base-package="com.maya.comtroller" />
12
13     <!-- 配置视图解析器 -->
14     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
15         <!-- <property name="prefix" value="/WEB-INF/"></property> -->
16         <property name="prefix" value="/"></property>
17         <property name="suffix" value=".jsp"></property>
18     </bean>
19
20     <!-- 对于上传文件的解析器 -->
21     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
22         <!-- 上传文件的最大值, 单位是b -->
23         <property name="maxUploadSize" value="10240000"></property>
24         <!-- 上传的单个文件的大小限制 -->
25         <property name="maxUploadSizePerFile" value="1024000"></property>
26         <!-- 转换字符集 -->
27         <property name="defaultEncoding" value="utf-8"></property>
28     </bean>
29
30     <!-- 开启SpringMVC注解驱动 -->
31     <mvc:annotation-driven>
32         <!-- 改成false, 原因是在spring中默认使用的json格式的转换器是Jackson.jar中的转换器, 但实际开发中更受欢迎的是fastjson.jar -->
33         <mvc:message-converters register-defaults="false">
34             <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
35             <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
36             <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter" />
37             <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
38             <bean id="fastJsonHttpMessagerConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
39                 <!-- 设置支持的媒体类型 -->
40                 <property name="supportedMediaTypes">
41                     <list>
42                         <value>text/html; charset=utf-8</value>
43                         <value>application/json; charset=utf-8</value>
44                     </list>
45                 </property>
46             </bean>
47         </mvc:message-converters>
48     </mvc:annotation-driven>
49 </beans>


controller层:

1 package com.maya.comtroller;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.util.Date;
6
7 import javax.servlet.http.HttpServletRequest;
8
9 import org.apache.commons.io.FileUtils;
10 import org.springframework.http.HttpHeaders;
11 import org.springframework.http.HttpStatus;
12 import org.springframework.http.MediaType;
13 import org.springframework.http.ResponseEntity;
14 import org.springframework.stereotype.Controller;
15 import org.springframework.web.bind.annotation.RequestMapping;
16 import org.springframework.web.bind.annotation.RequestParam;
17 import org.springframework.web.multipart.MultipartFile;
18
19 @Controller
20 @RequestMapping("file")
21 //上传文件
22 public class TestFileController {
23     @RequestMapping("/testUpload")
24     public String testUpload(
25             HttpServletRequest request,
26             @RequestParam("myfile")
27             MultipartFile file,
28             String desp) throws IllegalStateException, IOException {
29
30         String path =
31                 request.getServletContext().getRealPath("/MyFiles/");
32
33         Date date = new Date();
34
35         String orgFileName = date.getTime()+ "";
36
37         String typeName = file.getOriginalFilename();
38
39         String orgTypeName = typeName.substring(typeName.lastIndexOf("."));
40
41         System.out.println(path);
42         // 上传文件的源文件名
43         File orgFile = new File(path + "/" + orgFileName + orgTypeName);
44
45         file.transferTo(orgFile);
46
47         return "success";
48     }
49
50     //下载文件
51     @RequestMapping("/downloadFile")
52     public ResponseEntity<byte[]> testDownLoad(
53             HttpServletRequest request,
54             String filename) throws Exception {
55
56         String orgFilename = new String(filename.getBytes("iso-8859-1"), "utf-8");
57
58         String path =
59                 request.getServletContext().getRealPath("/myfiles/");
60
61         File orgFile = new File(path + "/" + orgFilename);
62
63         // 设置请求头信息
64         HttpHeaders hh = new HttpHeaders();
65         // 告诉前台, 以(attachement, 就是下载)的方式打开文件
66         hh.setContentDispositionFormData("attachment", new String(orgFilename.getBytes("utf-8"), "iso-8859-1"));
67         // 以二进制流的形式传输文件, 这是最常见的下载方式
68         hh.setContentType(MediaType.APPLICATION_OCTET_STREAM);
69
70         return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(orgFile), hh,
71                 HttpStatus.CREATED);
72     }
73
74 }


jsp页面:

1 <%@ page language="java" contentType="text/html; charset=utf-8"
2     pageEncoding="utf-8" import="java.io.File"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
7 <title>Insert title here</title>
8 </head>
9 <body>
10 <div style="margin:100px">
11 <form action="file/testUpload.do" method="post" enctype="multipart/form-data">
12     <input name="desp" />
13     <input type="file" multiple="multiple" name="myfile" /><br>
14     <input type="submit" value="Submit" />
15 </form>
16
17 <hr>
18 <%
19     String path = request.getServletContext().getRealPath("/MyFiles/");
20     File f = new File(path);
21     File[] files=f.listFiles(); //获取路径下的文件名
22     for(File fi:files){
23         out.print("<a href='file/downloadFile.do?filename="+fi.getName()+"'>"+fi.getName()+"</a><br>");
24     }
25 %>
26 </div>
27 </body>
28 </html>


这种方式只能进行单文件的上传,不建议使用该方式进行多文件上传,应考虑其他方式。如果要使用该方式进行多文件上传,可以,使用如下代码:

from表单中增加一个

multiple="multiple"


1     <form action="<%=basePath %>/file/testUpload.do" method="post"
2         enctype="multipart/form-data">
3         <input name="myfile" multiple="multiple" type="file" /><input type="submit"
4             value="Submit" />
5     </form>


后台:

1 @Controller
2 @RequestMapping("file")
3 public class TestFileController {
4     @RequestMapping("/testUpload")
5     public String testUpload(
6             HttpServletRequest request,
7             @RequestParam("myfile")
8             MultipartFile[] files,
9             String desp) throws IllegalStateException, IOException {
10
11         String path =
12                 request.getServletContext().getRealPath("/files/");
13
14         for(MultipartFile file : files) {
15             Date date = new Date();
16             String orgFileName = date.getTime()+ "";
17             String typeName = file.getOriginalFilename();
18             String orgTypeName = typeName.substring(typeName.lastIndexOf("."));
19             File orgFile = new File(path + "/" + orgFileName + orgTypeName);
20             file.transferTo(orgFile);
21         }
22     }


但是,如果在上传成功之后的提示页面通过超链接返回文件上传页面,会报404错

因为有注解

@RequestMapping("file")


定义了请求的前缀是指向 file 下的,所以执行方法最后返回的时候,会从 file 下去寻找视图层的页面,所以无法找到

解决方法:

可以通过上下文路径:

1 <%
2     String basePath = request.getContextPath(); // 上下文路径
3 %>


1     <%=basePath %>


获取当前项目名,并写在请求的路径中

1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2     pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>Insert title here</title>
8 <%
9     String basePath = request.getContextPath(); // 上下文路径
10 %>
11 </head>
12 <body>
13 上传成功 !
14 <a href="<%=basePath %>/filetest.jsp">返回文件页面</a>
15 </body>
16 </html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: