1、pom.xml 中添加文件上传包
<!-- 上传文件包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2、 springMVC 容器中创建 multipartResolver 对象
<!-- 文件上传解析器,将上传的文件封装为MultipartFile -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/> <!-- 默认编码 -->
<property name="maxUploadSize" value="102400000"/> <!-- 文件最大值 -->
<property name="maxInMemorySize" value="4096"/> <!-- 缓存大小 -->
<property name="uploadTempDir" value="shxt"/> <!-- 临时文件夹 -->
</bean>
3、前端设置文件上传表单
<form action="/upload" enctype="multipart/form-data" method="POST">
<input type="file" name="file"/>
<input type="submit" value="提交" />
</form>
4、controller 代码参考如下
@RequestMapping("/upload")
@ResponseBody
public String testUp(@RequestParam("file") MultipartFile photo,HttpSession session) throws IOException {
ServletContext servletContext = session.getServletContext();
String photoPath = servletContext.getRealPath("/file");
File file = new File(photoPath);
if( !file.exists()){
file.mkdir();
}
String fileName = photo.getOriginalFilename();
String stffixName = fileName.substring(fileName.lastIndexOf("."));
UUID uuid = UUID.randomUUID();
String finalName = uuid + stffixName;
while( new File(finalName).exists()){
uuid = UUID.randomUUID();
finalName = uuid + stffixName;
}
String finalPath = photoPath + File.separator + finalName;
photo.transferTo( new File(finalPath));
return "success";
}
|