Spring MVC多段文件上传

17 篇文章 0 订阅
4 篇文章 0 订阅

 从web.xml开始,申明:现在只做了可以上传了,还有细节没有做好。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>springMVC</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>



</web-app>

相应要在web-inf/spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
        "http://www.springframework.org/dtd/spring-beans-2.0.dtd">


<beans>

	<!-- lets use the Commons-based implementation of the MultipartResolver 
		interface -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="10000000000"></property>
	</bean>

	<bean id="urlMapping"
		class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<value>
				/upload.do=fileUploadController
			</value>
		</property>
	</bean>

	<bean id="fileUploadController" class="com.spring.mvc.controller.FileUploadController">
		<property name="commandClass" value="com.spring.mvc.controller.FileUploadBean">
		</property>
		<property name="formView" value="tranf.jsp" />
		<property name="successView" value="success.jsp" />
	</bean>

</beans>




 

formView:form视图;

successView:成功视图;

fileUploadController :控制器;

package com.spring.mvc.controller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

@SuppressWarnings("deprecation")
public class FileUploadController extends SimpleFormController {

	static Log log = LogFactory.getLog(FileUploadController.class);

	private String uploadDir;

	/**
	 * well, let's do nothing with the bean for now and return cast the bean
	 * let's see if there's content there
	 */
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws ServletException, IOException, Exception {

		FileUploadBean bean = (FileUploadBean) command;

		byte[] bytes = bean.getFile();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		@SuppressWarnings("rawtypes")
		Iterator iter = multipartRequest.getFileNames();
		while (iter.hasNext()) {
			String fileName = (String) iter.next();
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
					.getFile(fileName);
			if (file.getSize() != 0) {
				String uploadDir = this.getUploadDir();
				File dirPath = new File(uploadDir);
				if (!dirPath.exists()) {
					dirPath.mkdirs();
				}
				String sep = System.getProperty("file.separator");
				if (log.isDebugEnabled()) {
					log.debug("uploading to: " + uploadDir + sep
							+ file.getOriginalFilename());
				}
				File uploadedFile = new File(uploadDir + sep
						+ file.getOriginalFilename());
				FileCopyUtils.copy(bytes, uploadedFile);
				System.out.println("********************************");
				System.out.println(uploadedFile.getAbsolutePath());
				System.out.println(bytes.length);
			}
		}

		return super.onSubmit(request, response, command, errors);
	}

	/**
	 * to actually be able to convert Multipart instance to byte[] we have to
	 * register a custom editor now Spring knows how to handle multipart object
	 * and convert them
	 */
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws ServletException {

		binder.registerCustomEditor(byte[].class,
				new ByteArrayMultipartFileEditor());
	}

	public String getUploadDir() {
		uploadDir = "E:/logs";
		return uploadDir;
	}

	public void setUploadDir(String uploadDir) {

		this.uploadDir = uploadDir;
	}

}

上传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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

	<h1>please select a file</h1>
	<form method="post" action="upload.do" enctype="multipart/form-data">
		<input type="file" name="file" /> <input type="submit" />
	</form>


</body>
</html>

加入的jar包有:

commons-logging-api-1.1.jar

org.springframework.web.servlet-3.0.5.RELEASE.jar


commons-logging-1.0.4.jar

org.springframework.web-3.0.5.RELEASE.jar


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值