我在网上找到了这个 servlet java,它从 2 级的 xmlHttpRequest 上传图像。现在,在 servlet 中,我拥有具有我需要的所有特征的图像对象:名称、大小、尺寸、ecc ......现在我想要将图像存储在服务器的目录中。我能怎么做?
servlet 的代码如下(不是我的):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String ajaxUpdateResult = "";
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
ajaxUpdateResult += "Field " + item.getFieldName() +
" with value: " + item.getString() + " is successfully read\n\r";
} else {
String fileName = item.getName();
InputStream content = item.getInputStream();
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
// Do whatever with the content InputStream.
System.out.println(item.getSize());
//System.out.println(Streams.asString(content));
ajaxUpdateResult += "File " + fileName + " is successfully uploaded\n\r";
}
}
} catch (FileUploadException e) {
throw new ServletException("Parsing file upload failed.", e);
}
response.getWriter().print(ajaxUpdateResult);
}