SSSLINPPP
1. Summary
Spring MVC provides the most direct support for file uploads, which is implemented through plug-and-play multipartresolve. Spring uses Jakarta Commons FileUpload technology to implement a Multipartresolver implementation class: Commonsmultipartresolver.
The following is a detailed explanation of how spring MVC implements file uploads.
2. Add a jar package
to upload a Spring mvc file, you need to add the following two jar packages:
- Commons-fileupload-1.2.2.jar;
- Commons-io-2.0.1.jar
3. Configure Commonsmultipartresolver
<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8" p:maxUploadSize="5000000" p:uploadTempDir="upload/temp" />
Description
- P:defaultencoding= "UTF-8": here Set the default file encoding to UTF-8, must be consistent with the default encoding of the user JSP;
- P:maxuploadsize= "5000000": Specify the file upload size, in bytes;
- P:uploadtempdir= "upload/temp": File upload temporary directory, upload completed, the temporary files will be deleted;
4. Control Layer Code
Front Desk Request: Http://localhost:8080/SpringMVCTest/test/uploadPage.action, return to the Uploadpage.jsp interface, as follows:
@RequestMapping(value = "/upload")
public String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file,
HttpServletRequest request, ModelMap model) throws Exception {
if (!file.isEmpty()) {
// 保存文件-方式1 --测试过,可以用,必须先创建相应目录
// file.transferTo(new File("d:/"+file.getOriginalFilename()));
// 保存文件-方式2
String path = request.getSession().getServletContext()
.getRealPath("upload");
String fileName = file.getOriginalFilename();
File targetFile = new File(path, fileName);
//目录不存在,则创建目录
if(!targetFile.exists()){
targetFile.mkdirs();
}
//保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);
return "success";
} else {
return "fail";
}
}
5. File Upload JSP
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<title>请上传用户头像</title>
<body>
请选择上传的头像文件
<form method="post" action="<c:url value="/test/upload.action"/>"
enctype="multipart/form-data">
<input type="text" name="name" />
<input type="file" name="file" />
<input type="submit" />
</form>
</body>
Successfully returned interface:
6. Blogs
HTTP://WWW.CNBLOGS.COM/SSSLINPPP
Http://blog.sina.com.cn/spstudy
From for notes (Wiz)
List of attachments
"Spring Learning note-mvc-13" Spring MVC file Upload