SpringMVC文件上传

工作中,我们难免会遇到文件上传的需求。而这一功能在编写时如果处理不好,又很容易出错。所以今天博主在这里记录一下,基于 SpringMVC 框架下文件上传功能的实现方法。

UploadFileDemo.java

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.***.util.CommonDemo;

@Controller
@RequestMapping("/insertData")
@Scope("prototype")
public class UploadFileDemo {
	
	@RequestMapping("/insertExcel")
	@ResponseBody
	public Map<String, String> insertExcel(@RequestParam("file") MultipartFile file, 
		HttpServletRequest request){
		if(file != null){
			Map<String, String> result = new HashMap<String, String>();
			String outerFile = null;
			try {
				outerFile = CommonDemo.innerFile2OuterFile(file, 
					CommonDemo.getUUID()+file.getOriginalFilename());
				// 如需获取文件上传请求中的携带的其他参数可用 request 对象获取
				String parameter = request.getParameter("param");
				// 输出得到的参数
				System.out.println(parameter);
				// 获取持久化的文件
				File opFile = new File(outerFile);
				// 可在此处对 opFile 进行一顿猛如虎的操作
				//       .
				//       .
				//       .
				// 操作结束,来颗烟放松一下
				result.put("result", "SUCCESS");
			} catch (Exception e) {
				result.put("result", "FAILED");
				e.printStackTrace();
			}finally{
				// 如果对文件进行解析后别无它用,可在此处进行文件删除。
				File tempExcel = new File(outerFile);
				if(tempExcel.exists()){
					tempExcel.delete();
				}
			}
			return result;
		}
		return null;
	}
	
}  

CommonDemo.java

import java.io.File;
import java.util.UUID;

import org.springframework.web.multipart.MultipartFile;


/**
 * @ClassName: CommonDemo
 * @author Supreme_Sir
 * @date 2019年4月30日 下午4:09:06
 */
public class CommonDemo {
	
	/**
	 * 将上传的图片保存至本地项目图片目录
	 * 
	 * @Title: innerFile2OuterFile 
	 * @param file
	 * @param fileName
	 * @return
	 * @throws Exception    
	 * String    
	 * @throws
	 */
	public static String innerFile2OuterFile(MultipartFile file, String fileName) throws Exception {
		String realpath = getProjectRealpath();
		if (file != null) {
			File localFile = new File(realpath += "common\\file\\" + fileName);
			file.transferTo(localFile);
		}
		return realpath;
	}

	/**
	 * 获取不含符号的UUID字符串
	 * 
	 * @Title: getUUID
	 * @return String
	 * @throws
	 */
	public static String getUUID() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	/**
	 * 获取项目在本地磁盘中的绝对路径
	 * 
	 * @Title: getProjectRealpath
	 * @return String
	 * @throws
	 */
	public static String getProjectRealpath() {
		StringBuffer sb = new StringBuffer();
		String[] splitPath = CommonDemo.class.getResource("/").toString().split("/");
		for (int j = 1; j < splitPath.length - 2; j++) {
			sb.append(splitPath[j] + "\\");
		}
		return sb.toString();
	}		
}  

spring-mvc.xml

<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器-->
<bean id="multipartResolver" 
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
    <!-- 默认编码 -->
    <property name="defaultEncoding" value="utf-8" />  
    <!-- 文件大小最大值 10M = 1024*1024*10 = 10485760 -->
    <property name="maxUploadSize" value="10485760" />  
    <!-- 内存中的最大值 -->
    <property name="maxInMemorySize" value="40960" />  
</bean>  

pom.xml

<!-- 上传组件包 start -->
<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.3.1</version>
</dependency>
<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.4</version>
</dependency>
<dependency>
	<groupId>commons-codec</groupId>
	<artifactId>commons-codec</artifactId>
	<version>1.10</version>
</dependency>
<!-- 上传组件包 end -->

PS:

  1. CommonDemo.getProjectRealpath() 获取的是项目在本地磁盘中的绝对路径,因此当使用 Eclipse 中的 Tomcat 对项目进行发布时,项目的真实类路径应该是在 Eclipse 插件中的一个子目录中而非 .java 文件所在的绝对路径。
  2. 查看项目发布后所在绝对路径的方式: Tomcat 启动后查看 Console 输出可见: validateJarFile(E:\****\***\Code\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\你的项目名称\WEB-INF\lib\javaee-api-7.0.jar)
OJBK!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值