Reputation: 3740
In Servlet 3.1 it is possible to upload multiple files to servlet in one request (like a bulk upload), but what I want to achieve is to upload a big number of files to servlet as soon as each one is created without creating a new request on every file. In other words, there are 1000 files created on runtime, and I do not want 1st one to wait for the creation of the last to be uploaded. I want each file uploaded immediately after creation, so that servlet can check the upload timestamp for each file (and send back the result). The hard part for me is, I want neither to wait for creating all of them, nor to use separate requests for each file.
Is that possible? If yes, please give me some tips and directions/sources.
Upvotes: 0
Views: 1008
Reputation: 42926
Yes, it is possible read multiple files in a single servlet request.
Here is how you could read the files in the servlet:
@WebServlet(urlPatterns = { "/UploadServlet" })
@MultipartConfig(location = "/uploads")
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
for (Part part : request.getParts()) {
String fileName = part.getSubmittedFileName();
out.println("... writing " + fileName");
part.write(fileName);
out.println("... uploaded to: /uploads/" + fileName);
}
}
}
Update: Based on your updated question, you have ~1000 files that you want to "stream" to the server as they are created. It's not possible to add more parts to an existing post request, and I think it would be a bit excessive to try and upload all 1000 files in a single POST request anyway.
I recommend setting some arbitrary chunk size (say 20 files at a time for example) and batch them up and make a POST requests for every 20 files. This way, you are not waiting for all 1000 files to be created, and you are not doing everything over a single POST request. This will allow you to "stream" your files to the server in 20 file increments.
Upvotes: 2