配置虚拟目录
配置好虚拟路径后,我们可以通过虚拟路径来访问文件
编写Controller
@RequestMapping("/editItemSubmit")
public String editItemSubmit(MultipartFile pictureFile, Model model)throws Exception {
//原始文件名称
String pictureFile_name = pictureFile.getOriginalFilename();
//新文件名称
String newFileName = UUID.randomUUID().toString() + pictureFile_name.substring(pictureFile_name.lastIndexOf("."));
//上传图片
File uploadPic = new java.io.File("E:/workspace/ideapj/learnspringmvc/upload/temp/" + newFileName);
if (!uploadPic.exists()) {
uploadPic.mkdirs();
}
//向磁盘写文件
pictureFile.transferTo(uploadPic);
model.addAttribute("tp","/pic/temp"+newFileName);
return "upload";
}
编写jsp页面
<%--
Created by IntelliJ IDEA.
User: 黄维
Date: 2018/8/9
Time: 15:55
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form id="itemForm"
action="${pageContext.request.contextPath }/editItemSubmit.do"
method="post" enctype="multipart/form-data">
<img src="${tp}">
<input type="file" name="pictureFile">
<input type="submit" value="上传">
</form>
</body>
</html>
此时需要指定form表单的属性enctype为multipart/form-data
配置文件上传
<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="209715200" />
<property name="defaultEncoding" value="UTF-8" />
<property name="resolveLazily" value="true" />
</bean>