I have a servlet application that need to receive some files from some clients (in general not html\\javascript based!) and I have to limit the filesize for each file. Thisi is a classical problem.
The streaming API of the apache fileUpload allow to stream a multi-part request to the server avoiding the need of saving the request content in temporary files before they are processed. Is this Correct?
Anyway with this approach I obviously can't know the actual filesize.
What I though was:
Now assuming that I want to make all the necessary validations server-side. This because I'm paranoic and I don't trust the clients, then:
a. options (1) and (2) are useful in case "good" clients make bad requests. So a first validation can be based on that. b. option (3) is the only completely server-side option I found. So it is needed.
So I though that I could count the bytes I read and if the file exceedes the size-limit I print errors, delete the file I was writing and then make the "return" in servlet doPost. Am I doing right or there are some other better way to go?
Try like this into your Servlet, also get all information about file from item
//TODO Create and check tmpDir & destinationDir then do as below
PrintWriter out = response.getWriter();
response.setContentType("text/xml;charset=UTF-8");
File file = null;
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
fileItemFactory.setSizeThreshold(10 * 1024 * 1024);
fileItemFactory.setRepository(tmpDir); /* Set the temporary directory for uploaded files of size above threshold. */
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.getSize() <######||item.getSize() > 0){ // Where you can control file size
if (item.isFormField()) {
System.out.println("Field = " + item.getFieldName() + ", Value = " + item.getString());
} else {
System.out.println("Field Name = " + item.getFieldName() + ", File Name = " + item.getName() + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize());
file = new File(destinationDir, item.getName()); ///Destination for permanent save*/
item.write(file);
}
out.println("Upload success");
}else{
out.println("File Size is not be zero OR more than ####");
}
}
} catch (FileUploadException ex) {
out.println("Upload Failed" + ex.getMessage());
log("Error while parsing the request", ex);
} catch (Exception ex) {
out.println("Upload Failed" + ex.getMessage());
log("Error while uploading file", ex);
}
out.close();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.