How to HttpServletRequest file objects and store them
- 2021-08-06 20:30:14
- OfStack
Core code
Because HttpServletRequest cannot directly fetch the file data, it is cast to MultipartHttpServletRequest
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List < MultipartFile > files = multipartRequest.getFiles("files");
POST
/* Submit a form */
function myupload() {
$.ajax({
url:"/exUploadController.do?uploadTest",
type : "POST",
async: false,
cache: false, // Set here false
contentType: false,// You must set false ,formupload1 You must set the enctype="multipart/form-data"
processData: false, // You must set fals
data :new FormData(document.getElementById("myForm")),
success:function (data) {
alert(data);
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
})
}
Servlet
HttpServletRequest request;
// Get uploaded pictures
MultipartHttpServletRequest mureq = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> files = mureq.getFileMap();
MultipartFile file =null;
if (files != null &&files.size()> 0) {
Map.Entry<String, MultipartFile> f = files.entrySet().iterator().next();
file = f.getValue();
}
// Get the path of project deployment
String rootPath = request.getSession().getServletContext().getRealPath("/");
// Get the name of the uploaded picture
String fileName = file.getOriginalFilename();
// Gets the size of the uploaded picture
float size = file.getSize()
// In path Create under the path 1 Files
File newFile = new File(path);
// Determine whether the file exists
if(!newFile.exists()) {
newFile.mkdirs();// If it doesn't exist, open up 1 Individual space
}
// Store uploaded files
file.transferTo(newFile);