我创建了一个servlet 3.1 java应用程序,用户可以上传大文件(超过100MB)并发布到Heroku(免费套餐),但由于文件大小,它似乎在阻塞。
因此我将项目更改为使用servlet 2.5规范,但现在使用下面的代码(upload.parseRequest(request))时,上传文件列表始终为空。为什么呢?
public class EncodingController extends HttpServlet {
private static final long serialVersionUID = 1L;
// location to store file uploaded
private static final String UPLOAD_DIRECTORY = "upload";
// upload settings
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 200; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 200; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 400; // 50MB
/**
* @see HttpServlet#HttpServlet()
*/
public EncodingController() {
super();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(request)) {
// if not, we stop here
PrintWriter writer = response.getWriter();
writer.println("Error: Form must has enctype=multipart/form-data.");
writer.flush();
return;
}
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
// sets memory threshold - beyond which files are stored in disk
factory.setSizeThreshold(MEMORY_THRESHOLD);
// sets temporary location to store files
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// sets maximum size of upload file
upload.setFileSizeMax(MAX_FILE_SIZE);
// sets maximum size of request (include file + form data)
upload.setSizeMax(MAX_REQUEST_SIZE);
// constructs the directory path to store upload file
// this path is relative to application's directory
String uploadPath = getServletContext().getRealPath("")
+ File.separator + UPLOAD_DIRECTORY;
// creates the directory if it does not exist
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// parses the request's content to extract file data
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// iterates over form's fields
for (FileItem item : formItems) {
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
request.setAttribute("message",
"Upload has been done successfully!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message",
"There was an error: " + ex.getMessage());
}
// redirects client to message page
getServletContext().getRequestDispatcher("/message.jsp").forward(
request, response);
}
答案 0 :(得分:0)
使用以下代码解决问题:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("application/json");
PrintWriter out = response.getWriter();
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
IUploader uploader = new S3Uploader();
String fileUrl = uploader.sendFile(item.getInputStream(), item.getSize());
if (!fileUrl.isEmpty()) {
IEncoder encoder = new Zencoder();
out.append("{ 'encodedFile':" + encoder.encode(fileUrl) + "}");
response.setStatus(HttpServletResponse.SC_OK);
return;
}
}
}
} catch (Exception e) {}
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
out.append("{}");
}
}