我正在使用Apache Commons FileUpload将数据上传到我的服务器 - 一些文本字段和一个文件项。有时只有没有文件的文本字段,我也需要继续这个请求。当我尝试这样做时,org.apache.commons.fileupload.FileUploadException: Stream ended unexpectedly
出现在List fileItems = upload.parseRequest(request)
行上。
有我的代码:
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private int maxFileSize = 50*1024*1024;
private int maxMemSize = 40*1024;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
...
try {
...
isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory(maxMemSize,
new File(properties.getProperty("temp")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxFileSize);
UploadRequest uploadRequest = new UploadRequest();
try {
List fileItems;
// NEXT LINE EXCEPTION
fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
while(i.hasNext()){
FileItem item = (FileItem)i.next();
if(!item.isFormField()){
String fileName = item.getName();
}
else {
...
}
}
...
如果我发送文件和文本字段 - 我可以阅读所有字段。如果我不发送文件 - 我也不能因为例外而阅读文本字段。任何解决方案只加载没有multipart/form-data
文件的文本?