论坛首页 Java企业应用论坛

Spring Upload File 文件上传的使用

浏览 9016 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-04-14   最后修改:2009-04-22

Spring Upload method 文件上传

1. org.springframework.web.multipart.commons.CommonsMultipartResolver 包是Spring中用来处理的上传文件的,我们可以将配置在Spring-context.xml或者action-servlet.xml等配置文件,Spring会自己检查每次请求,如果请求中包含上传的form数据,则会利用此包来解析.例如下面配置:

	<!-- upload file -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize">
			<value>2048000</value>
		</property>
		<property name="maxInMemorySize">
			<value>2048</value>
		</property>
		<property name="defaultEncoding">
			<value>UTF-8</value>
		</property>
	</bean>

 它的设置参数如下:

 void cleanupMultipart(MultipartHttpServletRequest request) 
          Cleanup any resources used for the multipart handling, like a storage for the uploaded files. 
protected  String determineEncoding(HttpServletRequest request) 
          Determine the encoding for the given request. 
 DiskFileUpload getFileUpload() 
          Return the underlying org.apache.commons.fileupload.DiskFileUpload instance. 
 boolean isMultipart(HttpServletRequest request) 
          Determine if the request contains multipart content. 
protected  DiskFileUpload newFileUpload() 
          Initialize the underlying org.apache.commons.fileupload.DiskFileUpload instance. 
 MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) 
          Parse the given HTTP request into multipart files and parameters, and wrap the request inside a MultipartHttpServletRequest object that provides access to file descriptors and makes contained parameters accessible via the standard ServletRequest methods. 
 void setDefaultEncoding(String defaultEncoding) 
          Set the default character encoding to use for parsing requests, to be applied to headers of individual parts and to form fields. 
 void setMaxInMemorySize(int maxInMemorySize) 
          Set the maximum allowed size (in bytes) before uploads are written to disk. 
 void setMaxUploadSize(long maxUploadSize) 
          Set the maximum allowed size (in bytes) before uploads are refused 
 void setServletContext(ServletContext servletContext) 
          Set the ServletContext that this object runs in. 
 void setUploadTempDir(Resource uploadTempDir) 
          Set the temporary directory where uploaded files get stored. 

2. 下来就需要在action来自己处理解析过的文件

    可以来将request转成public interface MultipartHttpServletRequest,这个接口中提供了几个我们方便使用的方法

MultipartFile getFile(String name) 
          Return the contents plus description of an uploaded file in this request, or null if it does not exist. 
 Map getFileMap() 
          Return a Map of the multipart files contained in this request. 
 Iterator getFileNames() 
          Return an Iterator of String objects containing the parameter names of the multipart files contained in this request. 

 

如下:

    public void uploadSDFile(HttpServletResponse response, HttpServletRequest request) throws Exception {
    	 logger.info("upload sdfile action....");
    	 //remove session value for upload vlaue
    	if (request.getSession().getAttribute(Constants.IMPORT_SDF_PARSE_RESULT) != null)
    		 request.getSession().removeAttribute(Constants.IMPORT_SDF_PARSE_RESULT);
    	
    	// upload file
		MultipartHttpServletRequest mhs = (MultipartHttpServletRequest) request;
		MultipartFile mf = mhs.getFile("file");

		// get file
		File inputFile = FilePathHelper.uploadFile(mf, Constants.UPLOAD_SDF);

 取得MultipartFile,可以利用它的实现类org.springframework.web.multipart.commons.CommonsMultipartFile里众多的方法:

byte[] getBytes() 
          Return the contents of the file as an array of bytes. 
 String getContentType() 
          Return the content type of the file. 
 FileItem getFileItem() 
          Return the underlying org.apache.commons.fileupload.FileItem instance. 
 InputStream getInputStream() 
          Return an InputStream to read the contents of the file from. 
 String getName() 
          Return the name of the parameter in the multipart form. 
 String getOriginalFilename() 
          Return the original filename in the client's filesystem. 
 long getSize() 
          Return the size of the file in bytes. 
 String getStorageDescription() 
          Return a description for the storage location of the multipart content. 
protected  boolean isAvailable() 
          Determine whether the multipart content is still available. 
 boolean isEmpty() 
          Return whether the uploaded file is empty, that is, either no file has been chosen in the multipart form or the chosen file has no content. 
 void transferTo(File dest) 
          Transfer the received file to the given destination file. 

 
如下:

public static File uploadFile(MultipartFile mf, String uploadType) throws Exception {
		if (mf.isEmpty() || mf.getSize() <= 0)
			return null;
		CommonsMultipartFile cmf = (CommonsMultipartFile)mf;
		DiskFileItem fileItem = (DiskFileItem) cmf.getFileItem();
		String fileType = StringUtils.substringAfter(fileItem.getName(), ".");
		if (fileType.equalsIgnoreCase(uploadType)) {
			File file = fileItem.getStoreLocation();
			fileItem.write(file);
			return file;
		}
		return null;
	}

 org.apache.commons.fileupload.FileItemDefaultFileItem, DiskFileItem 实现类,里面有很多方法,方便我们使用.

 

需要注意是在form提交时,如果用form套form可能会有问题,解决的方法就是用jquery里面ajaxfileupload.

另外如果使用ajax提交方式的话,最好是用异步提交先将文件上传,解析的文件可以放到session中, 之后在callback函数中判断是否上传成功再做下步文件处理.

 

Note:若出现

2009-4-22 16:38:55 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet action threw exception
java.lang.ClassNotFoundException: org.apache.commons.io.output.DeferredFileOutputStream
 at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)

 

是因为缺少一个apache的包:commons-io-1.4.jar  见附件

 

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics