Доброе утро,
Я хотел бы спросить, как можно загрузить несколько файлов в одном теге формы, в частности, используя сервлет в качестве обратного вызова.Я уже перепробовал все решения в Интернете, но ни одно из них, похоже, не работает.
В настоящее время мой код -
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);
// }
// }
}
, закомментированные строки - еще одно решение, которое я пробовал.
Есть предложения?Заранее спасибо