- 文件上传需要导入两个jar包
commons-fileupload-1.3.1.jar
commons-io-1.3.2.jar - spring-mvc.xml文件配置文件上传的属性
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10485760000" />
<property name="maxInMemorySize" value="40960" />
</bean>
- 前端页面的form表单 提交方式必须是post 必须添加enctype=“multipart/form-data”
<form action="${pageContext.request.contextPath}/upFile" method="post" enctype="multipart/form-data">
<div class="form-group">
<lable>文件:</lable>
<div class="form-group">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<input type="submit" value="提交" class="btn btn-success">
</div>
</form>
- 编写后端代码
@Controller
public class UploadFile{
@RequestMapping("/upFile")
@ResponseBody
public void addFile(HttpServletRequest req, HttpServletResponse resp, MultipartFile file) throws IOException {
String filename = file.getOriginalFilename();
String realPath = req.getServletContext().getRealPath("/");
UUID uuid = UUID.randomUUID();
String newFileName = uuid.toString()+filename.substring(filename.lastIndexOf("."));
String upFilePath = realPath + File.separator+"file"+File.separator+newFileName;
System.out.println("upFilePath::"+upFilePath);
File file1 = new File(upFilePath);
if(!file1.exists()){
file1.mkdirs();
}
file.transferTo(file1);
resp.setContentType("text/html;charset=utf-8");
resp.setCharacterEncoding("utf-8");
resp.getWriter().write("success");
}
}