Multiple File upload using single servlet request

2020-02-12 08:45发布

问题:

I want to offer to upload multiple files clicking upload button only once. Can I use multipart to send files? If yes, then how?

P.S.: I don't want to use flash or send one file at a time.

回答1:

In you HTML, you can do the following :

<input accept="image/jpeg,image/gif,image/png" type="file" name="upload[]" multiple/>

adding multiple to the end of your input grants you what you want.



回答2:

Hope This Helps...

//JSP File

<html>
<head><title>Upload page</title></head></p> <p><body>
<form action="upload_file" method="post" enctype="multipart/form-data" name="form1" id="form1">
<center>
 Specify file: <input name="file" type="file" id="file">
 Specify file: <input name="file" type="file" id="file">
 Specify file:<input name="file" type="file" id="file">
 <input type="submit" name="Submit" value="Submit files"/>
<center>
</form>
</body>
</html>


//Servlet Page

import java.util.List;
import java.util.Iterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
   if (!isMultipart) {
   }
   else{
      FileItemFactory factory = new DiskFileItemFactory();
      ServletFileUpload upload = new ServletFileUpload(factory);
      List items = null;
      try {
          items = upload.parseRequest(request);
          } catch (FileUploadException e) {
               e.printStackTrace();
          }
      Iterator itr = items.iterator();
      while (itr.hasNext()) {
           FileItem item = (FileItem) itr.next();
           if (item.isFormField()) {
           } else {
           try {
              String itemName = item.getName();
              File savedFile = new File(config.getServletContext().getRealPath("/")+"uploadedFiles/"+itemName);
              item.write(savedFile);
              out.println("<tr><td><b>Your file has been saved at the loaction:</b></td></tr><tr><td><b>"+config.getServletContext().getRealPath("/")+"uploadedFiles"+"\\"+itemName+"</td></tr>");
              } catch (Exception e) {
                   e.printStackTrace();
              }
       }
}


回答3:

Yes, you can. Try apache fileupload library, you may refer to this question on stackoverflow: Multiple file upload in Jsp using Apache commons file upload API or this full example. Also you may take use of Spring by referencing this article.