SoFunction
Updated on 2025-04-05

JSP upload file to specified location instance code


/** Directly get the uploaded File */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
String targetPath = (()); // Target storage path, under the server deployment directory
  ("UTF-8");
  try {
   DefaultFileItemFactory factory = new DefaultFileItemFactory();
   DiskFileUpload up = new DiskFileUpload(factory);
   List<FileItem> ls = (request);
   for (FileItem file : ls) {
if (()) { // Determine whether it is a file or text information
("Form parameter name:" + ()+ ", form parameter value:" + ("UTF-8"));
    } else {
if (() != null && !().equals("")) { // Determine whether the file has been selected
File sFile = new File(());// Construct a temporary object, and the file is temporarily stored in the server's memory at this time
      File tFile = new File(targetPath, ());
      if(()){
("The file with the same name has been uploaded!");
      }else{
//(sFile, tFile);// Directly copy and upload to the server, automatically generate the on-machine directory, the directory name is the same as the name of the uploaded file
(sFile, tFile); // Directly copy and upload files to the server, and directly generate target files at the specified location
("File upload successfully");
if (()) { // Delete the uploaded file
        (tFile);
       } else if (()) {
        ();
       }
("File deletion succeeded");
      }
     } else {
("Upload file is not selected!");
     }
    }
   }
  } catch (FileUploadException e) {
("File upload failed!");
   ();
  }
 }