SpringMVC之文件上传

第一步:导入文件上传的jar包

在这里插入图片描述

第二步:在springMVC.xml配置文件上传相关配置

<!-- 配置文件上传配置 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 配置文件上传的编码 -->
		<property name="defaultEncoding" value="utf-8"></property>
		<!-- 配置文件上传大小 -->
		<property name="maxUploadSize" value="1048576"></property>
	</bean>

1048576 = 1024*1024

第三步:如果表单中有file控件,则必须指定

enctype="multipart/form-data"

单文件上传

package cn.java.controller.app;


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

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.junit.Test;
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 org.springframework.web.multipart.MultipartRequest;

import cn.java.utils.FilesUpload;

/**
 * @Description: TODO
 * @Title:  TestController.java
 * @author: Matthew
 * @date: 2019年3月16日 下午6:50:12
 * @version V1.0
 */
@Controller
@RequestMapping(value="/upload/")
public class Test2Controller {
	/**
	 * Description:单文件上传
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping("singleFileUpload")
	@ResponseBody
	public void singleFileUpload(@RequestParam(name="bigHeadImage" )MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException{
		//1.getOriginalFilename()获取上传文件的文件名
		String originalFilename = file.getOriginalFilename();
		//2.getName()获取表单中file控件的name属性值,此处的属性值为bigHeadImage
		String name = file.getName();
		System.out.println("file.getOriginalFilename:" + originalFilename);
		System.out.println("file.getName:" + name);
//		3.将上传的文件保存到指定的目录下
		String uuid = UUID.randomUUID().toString();

		String path = request.getServletContext().getRealPath("/upload");
		System.out.println(path);
		//注释里的是动态地址当你重启服务器时文件会丢失,固定地址当你重启服务器时不会丢失。
		File filePath = new File(/*path + */"E:\\apache-tomcat-9.0.11\\wtpwebapps\\upload\\" + uuid + originalFilename);
		file.transferTo(filePath);
	}

}

文件存储路径

	@RequestMapping("getUploadPath")
	public void getUploadPath(HttpServletRequest request){
//		String path = request.getRealPath("/upload");pageContext--->request--->session--->application(ServletContext)
		ServletContext sContext = request.getServletContext();
		String path = sContext.getRealPath("/upload");
		System.out.println(path);
	}

request的getRealPath已经被废弃,因此我们用application的,getRealPath的参数为你要上传的路径,然后他会将你前面的路径补全,这个路径最终是指向tomcat(服务器)的文件夹中的。

同名文件上传问题

如果一个用户上传了一个1.gif图片而另一用户也上传了这个名字的图片,但是图片的内容不一样,但是服务器只会存储第一个传入的图片,这样图片就会丢失,因此我们要将用户每次上传的图片重新命名,这个世间无二的代号为UUID

/**
	 * Description:UUID可以生成不重复的序列号
	 */
	@Test
	public void testUUID(){
		//网口号 + 时间戳
		String uuid = UUID.randomUUID().toString();
		System.out.println(uuid);
	}

因此我们在原本的图片名前加上uuid就防止了这种事情的发生。

在这里插入图片描述

文件丢失问题

当我们程序员在作测试时,用的时自己电脑,而服务器会时常关闭,因此当我们再次开启时服务器里的文件会被删除,因此我们测试时应该使用固定地址,而上线时再换回动态地址。

![在这在这里插入图片描述

多文件上传

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isELIgnored="false"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript">

</script>
</head>
<body>
	<form action="<%=basePath %>/upload/mutipleFileUpload.shtml" method="post" enctype="multipart/form-data">
		<p>大头照:<input type="file" name="bigHeadImage"></p>
		<p>小头照:<input type="file" name="smallHeadImage"></p>
		<p>光头照:<input type="file" name="noHeadImage"></p>
		<p><input type="submit" value="上传"></p>
	</form>
</form>
</body>
</html>
	/**
	 * Description:多文件上传
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping("mutipleFileUpload")
	public void mutipleFileUpload(MultipartRequest files,HttpServletRequest request) throws IllegalStateException, IOException{
		Map<String, Object> filesPath = FilesUpload.uploadFiles(request,files);
		System.out.println(filesPath);
	}
package cn.java.utils;

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

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

/**
 * @Description: TODO
 * @Title:  FilesUpload.java
 * @author: Matthew
 * @date: 2019年3月17日 下午8:16:26
 * @version V1.0
 */

public class FilesUpload {
	/**
	 * 
	 * Description:多文件上传
	 *
	 * @param request
	 * @param files
	 */
	public static Map<String, Object> uploadFiles(HttpServletRequest request,MultipartRequest files){
		Map<String, Object> filesInformation = new HashMap<String, Object>();
		Map<String, MultipartFile> filesMap = files.getFileMap();
		Set<String> keySet = filesMap.keySet();
		for(String key : keySet){
			MultipartFile file = filesMap.get(key);
			String originalFile = file.getOriginalFilename();//获取文件名
			String uuid = UUID.randomUUID().toString();
			String postFilePath = uuid + originalFile;
			File filePath = new File("E:\\apache-tomcat-9.0.11\\wtpwebapps\\upload\\" + postFilePath);
			try {
				file.transferTo(filePath);
			} catch (Exception e) {
				e.printStackTrace();
			}
			filesInformation.put(uuid, postFilePath);
		}
		return filesInformation;
	}
}

由于多文件上传我们将多次使用,因此可以抽取到工具类中,返回值以map形式返回为上传的uuid+文件路径。
在这里插入图片描述
我们可以选择同一图片上传多次
返回值
{259a0a33-78a2-472b-b016-12b0f93c5a35=259a0a33-78a2-472b-b016-12b0f93c5a35error.gif,
50f12b65-7413-44c7-ba7f-db49308e9802=50f12b65-7413-44c7-ba7f-db49308e9802error.gif,
4a5b28ca-f5b3-4978-a9b0-a42450196603=4a5b28ca-f5b3-4978-a9b0-a42450196603error.gif}
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值