![](/img/trans.png)
[英]Determine the size of a file upload before reading it all in in the Apache FileUpload Streaming API
[英]The file-size detection in apache fileUpload streaming API
我有一个Servlet应用程序,需要从某些客户端接收一些文件(通常不是基于html \\ javascript!),而且我必须限制每个文件的文件大小。 这是一个经典的问题。
apache fileUpload的流API允许将多部分请求流传输到服务器,从而避免了在处理临时文件之前将请求内容保存在临时文件中的需求。 这个对吗?
无论如何,使用这种方法我显然都不知道实际的文件大小。
我虽然是:
现在假设我要在服务器端进行所有必要的验证。 这是因为我很偏执,而且我不信任客户,所以:
一种。 选项(1)和(2)在“好”客户提出错误请求时很有用。 因此,可以基于此进行首次验证。 b。 选项(3)是我发现的唯一完全服务器端选项。 因此这是必需的。
因此,尽管我可以计算读取的字节数,并且如果文件超出大小限制,我将打印错误,请删除正在写入的文件,然后在servlet doPost中进行“返回”。 我做对了还是还有其他更好的方法?
像这样尝试进入Servlet,还可以从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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.