Using common file upload to upload files in SSH project

Today, the project used to upload. What I store in my database is the URL of the file, so I have to do some processing in the background. I have written several times before uploading, and I feel that the amount of code is too large. Today, I searched the Internet, and it will be much easier to upload with common file upload. After groping for an afternoon, I finally got it done. The background code is as follows

//The uploaded file
private File upload;
//file name and type
private String uploadContentType;
private String uploadFileName;
/*This is the variable to be written in the action, you must write it, otherwise it will be very troublesome, Struts2 will automatically assign the file to be uploaded, the file name, type, etc.*/

/// The following is the processing method
public String uploadStaffImage() throws Exception{
	//Take the file name and path, rename the file name with uuid to prevent Chinese mess
	String fileName = UUID.randomUUID().toString();
        //intercept file type
        String fileType = this.uploadFileName.substring(this.uploadFileName.lastIndexOf("."), this.uploadFileName.length());
        //New file name
        String file = fileName + fileType;
        // My directory is under "StaffImg" folder
        String path = request.getSession().getServletContext().getRealPath("/StaffImg");
	InputStream is = new FileInputStream(getUpload());  
        //Create an output stream to generate a new file  
        OutputStream os = new FileOutputStream(path + "//" + file);  
        //write disk 
        IOUtils.copy(is, os);
        os.flush();  
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
        //Update the URL in the database
        String imgURL = "StaffImg/"+file;
        this.staffFileUpLoadService.updataStaffImgURL(this.staffId, imgURL);
	return SUCCESS;
}

A total of 13 lines of code, compared to the previous written to be a lot more concise, method use is relatively simple.

This method can only upload a single file. If you upload in batches, the idea is the same, and you should add a loop in the outer layer
instead

Read More: