您应该使用Apache Commons FileUpload的FileItemIterator。
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.io.InputStream;
..
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try {
ServletFileUpload upload = new ServletFileUpload();
res.setContentType("text/plain");
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
//regular form field
resp.getWriter().println(("Form:" + name + " : " + Streams.asString(stream));
} else {
//fileform field
resp.getWriter().println(("File:" +name + " : " + item.getName());
}
}
} catch (Exception ex) {
throw new ServletException(ex);
}
}