早上好
我想问一下如何在表单的单个标签上上传多个文件,尤其是使用Servlet作为回调。我已经在网络上尝试了所有解决方案,但是这些解决方案似乎都不起作用。
当前,我的代码是
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Part> fileParts = (List<Part>) request.getParts();
System.out.println(fileParts.size());
for(Part filePart : fileParts) {
if (filePart != null && filePart.getSize() > 0) {
System.out.println(filePart.toString());
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
String fileName = filePart.getSubmittedFileName();
InputStream fileContent = filePart.getInputStream();
File uploads = new File("/*the physical path on my machine*/");
File file = new File(uploads, fileName);
if(file.exists()) {
Files.deleteIfExists(file.toPath());
}
else {
Files.copy(fileContent, file.toPath());
}
}
}
// HttpSession session = request.getSession();
// boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//
// if (isMultipart) {
// FileItemFactory factory = new DiskFileItemFactory();
// ServletFileUpload upload = new ServletFileUpload(factory);
//
// try {
// LinkedList<String> files = new LinkedList<String>();
// List items = upload.parseRequest((RequestContext) request);
// Iterator iterator = items.iterator();
// while (iterator.hasNext()) {
// FileItem item = (FileItem) iterator.next();
//
// if (!item.isFormField()) {
// String fileName = item.getName();
// files.add(fileName);
//
// String root = getServletContext().getRealPath("/");
// File path = new File(root + "/uploads");
// if (!path.exists()) {
// boolean status = path.mkdirs();
// }
//
// File uploadedFile = new File(path + "/" + fileName);
// System.out.println(uploadedFile.getAbsolutePath());
// item.write(uploadedFile);
// }
// }
//
// session.setAttribute("file", files);
// request.setAttribute("uploadOK", true);
// request.getRequestDispatcher("upload.jsp").forward(request, response);
// } catch (FileUploadException e) {
// e.printStackTrace();
// request.setAttribute("uploadNO", true);
// request.getRequestDispatcher("upload.jsp").forward(request, response);
// } catch (Exception e) {
// e.printStackTrace();
// request.setAttribute("uploadNO", true);
// request.getRequestDispatcher("upload.jsp").forward(request, response);
// }
// }
}
注释行是我尝试的另一种解决方案。
有什么建议吗? 预先感谢