Spring MVC3.2 通過Servlet3.0實現文件上傳


Servlet3.0規范增加了對文件上傳的原生支持,這里記錄一下Spring MVC3通過Servlet3上傳文件的實現。

配置文件

applicationContext.xml

<!-- spring mvc3+servlet3上傳文件需要配置 --><beanid="multipartResolver"class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean>

web.xml中需要配置multipart-config片段

<!-- spring mvc --><servlet><servlet-name>SpringMvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/spring/appContext.xml,/WEB-INF/config/spring/appInterceptor.xml</param-value></init-param><multipart-config><max-file-size>52428800</max-file-size><max-request-size>52428800</max-request-size><file-size-threshold>0</file-size-threshold></multipart-config><load-on-startup>1</load-on-startup></servlet>

update.jsp上傳界面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><metahttp-equiv="Content-Type"content="text/html; charset=utf-8"><title>twovs.com測試servlet3+springmvc3.2上傳文件</title></head><body><h1>Please upload a file</h1><formmethod="post"action="http://www.twovs.com/test/up.htm"enctype="multipart/form-data"><inputtype="text"name="name"value="1111"/><inputtype="file"name="file"/><inputtype="submit"/></form></body></html>

UpdateTest4Servlet.java Spring MVC Controller

/**
 * $id: com.twovv.update.UpdateTest4Servlet.java by fjt 2013-2-15
 *
 * @version:0.1
 *
 * Copyright (c) 2013 twovv.com 
 */package com.twovv.update;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;/** @Class: UpdateTest4Servlet @TODO: 測試上傳 */@ControllerpublicclassUpdateTest4Servlet{/** 
     * @method: fileUpload() -by fjt
     * @TODO:  文件上傳
     * @return String
     */@RequestMapping(value="/test/up",method=RequestMethod.POST)publicString fileUpload(@RequestParamString name,@RequestParamMultipartFile file){////你自己的存儲邏輯//這里只打印一下接收到的信息System.out.println(name);/** 
         * file.getName()獲取不到文件名,只能拿到一個“file”字符串
         * Servlet3沒有提供直接獲取文件名的方法,可以從請求頭中解析出來:
         * file.getHeader("content-disposition")方法間接獲取得到。
         */System.out.println(file.getName());System.out.println(file.getSize());return"";}}

簡單的配置完成,現在可以通過訪問http://www.twovs.com/upload.jsp來測試通過servlet3.0的新特性來上傳文件了。

碰到的問題

Spring @RequestParam綁定不到值(獲取不到值)。

異常日志

2013-02-1504:05:02,862[DEBUG]-[org.springframework.web.servlet.DispatcherServlet]DispatcherServletwith name 'SpringMvc' processing POST request for[/ueditor/test/up.htm]2013-02-1504:05:02,869[DEBUG]-[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]Looking up handler method for path /test/up.htm
2013-02-1504:05:02,879[DEBUG]-[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]Returning handler method [public java.lang.String com.twovv.update.UpdateTest4Servlet.fileUpload(java.lang.String,org.springframework.web.multipart.MultipartFile)]2013-02-1504:05:02,879[DEBUG]-[org.springframework.beans.factory.support.DefaultListableBeanFactory]Returning cached instance of singleton bean 'updateTest4Servlet'2013-02-1504:05:02,895[DEBUG]-[org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor]Opening JPA EntityManagerinOpenEntityManagerInViewInterceptor2013-02-1504:05:03,055[DEBUG]-[org.hibernate.internal.SessionImpl]Opened session at timestamp:136087230292013-02-1504:05:03,112[DEBUG]-[org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver]Resolving exception from handler [public java.lang.String com.twovv.update.UpdateTest4Servlet.fileUpload(java.lang.String,org.springframework.web.multipart.MultipartFile)]: org.springframework.web.bind.MissingServletRequestParameterException:RequiredString parameter 'name'isnot present
2013-02-1504:05:03,118[DEBUG]-[org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver]Resolving exception from handler [public java.lang.String com.twovv.update.UpdateTest4Servlet.fileUpload(java.lang.String,org.springframework.web.multipart.MultipartFile)]: org.springframework.web.bind.MissingServletRequestParameterException:RequiredString parameter 'name'isnot present
2013-02-1504:05:03,118[DEBUG]-[org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver]Resolving exception from handler [public java.lang.String com.twovv.update.UpdateTest4Servlet.fileUpload(java.lang.String,org.springframework.web.multipart.MultipartFile)]: org.springframework.web.bind.MissingServletRequestParameterException:RequiredString parameter 'name'isnot present
2013-02-1504:05:03,119[DEBUG]-[org.springframework.web.servlet.DispatcherServlet]NullModelAndView returned to DispatcherServletwith name 'SpringMvc': assuming HandlerAdapter completed request handling
2013-02-1504:05:03,119[DEBUG]-[org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor]Closing JPA EntityManagerinOpenEntityManagerInViewInterceptor2013-02-1504:05:03,148[DEBUG]-[org.springframework.orm.jpa.EntityManagerFactoryUtils]Closing JPA EntityManager2013-02-1504:05:03,155[DEBUG]-[org.springframework.web.servlet.DispatcherServlet]Successfully completed request

異常原因:根據Spring3的提示,缺少multipart-config配置

In order to useServlet3.0 based multipart parsing, you need to mark the DispatcherServletwith a "multipart-config" section in web.xml,orwith a javax.servlet.MultipartConfigElementin programmatic Servlet registration,orincase of a custom Servletclass possibly with a javax.servlet.annotation.MultipartConfig annotation on your Servletclass.Configuration settings such as maximum sizes or storage locations need to be applied at that Servlet registration level asServlet3.0 does not allow for those settings to be donefrom the MultipartResolver.

解決辦法

按照提示需要在web.xml中配置的DispatcherServlet中添加multipart-config片段。

MultipartConfig所有的屬性都是可選的,具體屬性如下:

  • fileSizeThreshold int 當數據量大於該值時,內容將被寫入文件。

  • location String 存放生成的文件地址。

  • maxFileSize long 允許上傳的文件最大值。默認值為 -1,表示沒有限制。

  • maxRequestSize long 針對該 multipart/form-data 請求的最大數量,默認值為 -1,表示沒有限制。

1、location屬性,既是保存路徑(在寫入的時候,可以忽略路徑設定),又是上傳過程中臨時文件的保存路徑,一旦執行write方法之后,臨時文件將被自動清除。

2、上傳過程中無論是單個文件超過maxFileSize值,或者上傳總的數據量大於maxRequestSize值都會拋出IllegalStateException異常

參考:
Servlet 3.0's FileUpload Sample
Using a MultipartResolver with Servlet 3.0 
JSR 315: JavaTM Servlet 3.0 Specification 
JSR-000315 JavaTM Servlet 3.0

轉載自:http://www.sxrczx.com/t/article/a3fadb5bd6734a8891c4dad43510ca5e.htm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM