Spring MVC——文件上传

1. 导入jar包
commons-io-2.4.jar、
commons-fileupload-1.2.2.jar

2.在%tomcat根目录%/conf/server.xml中的<host>节点中配置tomcat虚拟目录
<!--
docBase:实际上传路径
path:虚拟路径,访问路径为:http://localhost:8088/image
-->
<Context docBase="E:zhaorong emp" path="/image" reloadable="false"/>

3.在spring-mvc.xml配置解析器

<!-- 文件上传 : id名称必须给multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置文件的最大大小 (以byte字节为单位) 10M-->
<property name="maxUploadSize" value="10485760"></property>
</bean>

4.编写上传页面index.jsp
<form action="upload.action" method="post" enctype="multipart/form-data">

图片:<input type="file" name="multipartFile"><br/><br/>

<img src="http://localhost:8088/image/${fileName}"><br/><br/>

<input type="submit" value="上传">
</form>

5.编写controller代码
public String upload(Model model,MultipartFile multipartFile)//multipartFile名必须与页面的上传对象的名字相同

                              //也可以在一个from表单中上传其他类型的数据,但因为是以post类型提交,所以必须使用request获取
{
try {
System.out.println("保存文件对象:"+ multipartFile);

//原文件名称
String fileName = multipartFile.getOriginalFilename();//Tulips.jpg
System.out.println("原文件名:" + fileName);

//扩展名
String suffix = fileName.substring(fileName.lastIndexOf("."));
System.out.println("扩展名:" + suffix);

//新文件名称
String newFileName = UUID.randomUUID() + suffix;
System.out.println("新文件名:" + newFileName);

//上传路径
File dest = new File("E:\zhaorong\temp\"+newFileName);

//上传
multipartFile.transferTo(dest);

//保存文件名称
model.addAttribute("fileName", newFileName);

} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}

return "index";
}
6.测试
http://localhost:8088/springMvc_07_fileupload/index.jsp

原文地址:https://www.cnblogs.com/ccw95/p/6169597.html