SpringMVC文件上传,代码,配置相关信息

1,倒入包:两个

2,在springMVC配置文件

 <!-- 多部分文件上传 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     <property name="defaultEncoding" value="UTF-8"/><!-- 默认编码(ISO-8859-1) -->
     <property name="maxInMemorySize" value="4096" /><!-- 最大内存大小(10240) -->
     <property name="maxUploadSize" value="-1" /><!-- 最大文件大小,单位是字节,-1位无限 -->
     <property name="uploadTempDir" value="/upload/"/><!-- 上传后的目录 -->

3,表单 修改enctype

<form action="fileUpload" method="post" enctype="multipart/form-data">
	<label><input type="file" name="file" /></label>
	<label><input type="text"name="desc"/></label>
	<button>上传</button>
</form>

4,写handler

@RequestMapping(value="/fileUpload",method = RequestMethod.POST)
		public String fileUpload(String desc,MultipartFile file,Model m)
				throws IllegalStateException, IOException {
			System.out.println("upload.........."+file+"\n"+desc);
			if(file!=null && file.getOriginalFilename()!=null
					&&file.getOriginalFilename().length()>0) {
				String f="D:\\upload\\";
				String orgFileName=file.getOriginalFilename();
				String extendsName=orgFileName.substring(orgFileName.lastIndexOf("."));
				String newFileName=UUID.randomUUID().toString()+extendsName;
				File fl=new File(f+ newFileName);
				file.transferTo(fl);
				
				m.addAttribute("filePath", "/file/"+newFileName);
			}
			return "/user/success";
		}

5,添加虚拟路径

6,上传成功显示

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Success</h1>
<img alt="" src="${filePath }">
</body>
</html>

7,最后效果

发布了25 篇原创文章 · 获赞 0 · 访问量 508

猜你喜欢

转载自blog.csdn.net/luojiawen208/article/details/104994517