java implements the dynamic upload of multiple files and solves the file name problem

  • 2020-05-07 19:36:32
  • OfStack

This paper is divided into two aspects:

1. java realizes the dynamic uploading of multiple files

2. Solve the file renaming problem java

For your reference, the specific content is as follows

1. Upload multiple files dynamically


 <form name="xx" action="<c:url value='/Up3Servlet'/>" method="post" enctype="multipart/form-data">
  <table id="tb" border="1">
    <tr>
      <td>
        File : 
      </td>
      <td>
        <input type="file" name="file">
        <button onclick="_del(this);"> delete </button>
      </td>
    </tr>
  </table>
  <br/>
  <input type="button" onclick="_submit();" value=" upload ">
  <input onclick="_add();" type="button" value=" increase ">
  </form>
 </body>
 <script type="text/javascript">
   function _add(){
     var tb = document.getElementById("tb");
     // write 1 line 
     var tr = tb.insertRow();
     // Write columns 
     var td = tr.insertCell();
      // Write data 
     td.innerHTML="File : ";
     // The statement again 1 A new one td
     var td2 = tr.insertCell();
     // write 1 a input
     td2.innerHTML='<input type="file" name="file"/><button onclick="_del(this);"> delete </button>';
   }
   function _del(btn){
     var tr = btn.parentNode.parentNode;
     //alert(tr.tagName);
     // To obtain tr in table The subscript 
     var index = tr.rowIndex;
     // delete 
     var tb = document.getElementById("tb");
     tb.deleteRow(index);
   }
   function _submit(){
     // Go through all the files 
     var files = document.getElementsByName("file");
     if(files.length==0){
       alert(" There are no files to upload ");
       return false;
     }
     for(var i=0;i<files.length;i++){
       if(files[i].value==""){
         alert(" The first "+(i+1)+" File cannot be empty ");
         return false;
       }
     }
    document.forms['xx'].submit();
   }
 </script>
</html>

Iterate over all the files to be uploaded

2. Solve the problem of duplicate names of documents


package cn.hx.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

public class UpImgServlet extends HttpServlet {

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    String path = getServletContext().getRealPath("/up");
    DiskFileItemFactory disk = 
        new DiskFileItemFactory(1024*10,new File("d:/a"));
    ServletFileUpload up = new ServletFileUpload(disk);
    try{
      List<FileItem> list = up.parseRequest(request);
      // Receive only pictures *.jpg-iamge/jpege.,bmp/imge/bmp,png,
      List<String> imgs = new ArrayList<String>();
      for(FileItem file :list){
        if(file.getContentType().contains("image/")){
          String fileName = file.getName();
          fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
          
          // Access to extension 
          String extName = fileName.substring(fileName.lastIndexOf("."));//.jpg
          //UUID
          String uuid = UUID.randomUUID().toString().replace("-", "");
          // The new name 
          String newName = uuid+extName;     // Here with UUID To generate a new folder name so that it does not result in a new name 
          
          
          FileUtils.copyInputStreamToFile(file.getInputStream(),
              new File(path+"/"+newName));
          // In the list
          imgs.add(newName);
        }
        file.delete();
      }
      request.setAttribute("imgs",imgs);
      request.getRequestDispatcher("/jsps/imgs.jsp").forward(request, response);
    }catch(Exception e){
      e.printStackTrace();
    }
  
  }

}

The above implementation of java multi-file upload, to solve the file name problem, I hope to help you learn.


Related articles: