Spring MVC 的文件上傳
springmvc中web-xml中的配置
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/dispatcherServlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
在spring的applicationContext.xml中配置:
<!-- 上傳攔截,如最大上傳值及最小上傳值 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="10000000" /><!-- 10M -->
</bean>
在服務端有兩種方式獲取文件:
第一種:
<p>@RequestMapping(value = "/jsp/test/upload", method = RequestMethod.POST)// 將文件上傳請求映射到該方法
public String handleFormUpload(// 設置請求參數的名稱和類型
@RequestParam("file") CommonsMultipartFile mFile) { // 請求參數一定要與form中的參數名對應
if (!mFile.isEmpty()) {
log.info("上傳文件的名字:" + mFile.getOriginalFilename());
// String path = this.servletContext.getRealPath("/tmp/");
// //獲取本地存儲路徑
File file = new File("D:/myfile");
if (!file.exists()) file.mkdirs();
File file1 = new File("d:/myfile/" + new Date().getTime() + ".xls"); // 新建一個文件
try {
mFile.getFileItem().write(file1); // 將上傳的文件寫入新建的文件中
log.info("=======文件上傳成功====");
} catch (Exception e) {
e.printStackTrace();
}</p>
第二種 非注解的形式:
<!-- 啟動包掃描功能,以便注冊帶有@Controller、@Service、@repository、@Component等注解的類成為spring的bean -->
<context:component-scan base-package="com.ultrapower.portal" />
<!-- 啟動Spring MVC的注解功能 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
</bean>
<bean id="fileUploadController" class="com.ultrapower.portal.controller.FileUploadController">
<property name="exceptionFlowService" ref="exceptionFlowService"></property>
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<map>
<entry key="/home.do" value="homeController" />
<entry key="/jsp/upload.do" value="fileUploadController" />
</map>
</property>
</bean>
<!-- 頁面選擇 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" /> <!-- 前綴 -->
<property name="suffix" value=".jsp" /> <!-- 后綴 -->
</bean>
protected ModelAndView defaultHandler(HttpServletRequest request, HttpServletResponse response) throws Exception {
String message = "";
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// List items = upload.parseRequest(request);
try {
List items = upload.parseRequest(request);// 上傳文件解析
Iterator itr = items.iterator();// 枚舉方法
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {// 判斷是文件還是文本信息
log.info("表單參數名:" + item.getFieldName() + ",表單參數值:" + item.getString("UTF-8"));
}
else {
if (item.getName() != null && !item.getName().equals("")) {// 判斷是否選擇了文件
// item.getName()返回上傳文件在客戶端的名稱
log.info("上傳文件的大小:" + item.getSize() + ";上傳文件的類型:" + item.getContentType() + "上傳文件的名稱:"
- item.getName());
// 此時文件暫存在服務器的內存當中 把文件保存在服務器上
//
// File tempFile = new File(item.getName());// 構造臨時對象
// File file1 = new File("D:/xin");
// if (!file1.exists()) file1.mkdirs();
// File file = new File("D:/xin/",
// tempFile.getName());
// // if(file.getParentFile()==null)file.mkdirs();
// // 獲取根目錄對應的真實物理路徑
// item.write(file);// 保存文件在服務器的物理磁盤中
// InputStream in = new FileInputStream(file);
// request.setAttribute("upload.message", "上傳文件成功!");//</p>jsp頁面:
<body>
<h1>
Spring MVC 3.0 文件上傳測試
</h1>
<!-- //action里的html是后綴名,不是HTML文件,用于spring對請求進行攔截判斷-->
<form method="post" action="upload.do?method=fileUpload" enctype="multipart/form-data">其中method的是非注解的形式調用別的方法時傳遞的參數
<!-- <input type="text" name="name" />-->
<input type="file" name="file" />
<input type="submit" />
</form>
</body>