也许我的问题与这个问题无关,但我不知道如何处理多部分 HTTP 请求。
我写了一个 HTTP 请求,它使用 POST 发送一个文件和一个字符串。如何在我的 Servlet 的服务器端同时获取两者?
这就是我所做的。我走对了吗?
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
Status status = new Status();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
status.setSuccess(true);
status.setDescription("It is OK.");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MAX_MEMORY_SIZED);
factory.setRepository(new File(ADRESS_WHERE_I_WANT_TO_PUT_THE_FILE));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(MAX_FILE_SIZE_TO_BE_UPLOADED);
try {
List<FileItem> items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
... // WHAT TO DO HERE TO GET MY STRING AND MY FILE ???
}
}
else{
status.setSuccess(false);
status.setDescription("Not multipart.");
}
response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter output = response.getWriter();
output.write(gson.toJson(status));
output.flush();
}