Table of contents
Files uploaded with servlet can be renamed with a custom name. The method I am going to be using and explaining is simple and includes the following process:
- save the uploaded file to a temporary location.
- move the file from the temporary folder to the actual location.
With this basic introduction, let's hop into the real process.
Upload file
If you don't know how to upload a file, I suggest you read this article.
So, after uploading the file from HTML, we'll receive it from the servlet and save it to Temp
folder as below.
@MultipartConfig
Part fileParts = request.getPart("someFile"); //getPart() method accepts the value of name of the input tag.
String filename = fileParts.getSubmittedFileName(); //getSubmittedFileName() method returns the name of the file along with its extension
/**
* The code below creates a path to the UploadedImgs folder which is inside Images as shown below.
* Note that getRealPath() method gives the build path.
* Folder structure:
◼ Files
▪ UploadedFiles
▪ Temp
*/
// Path to temporary folder. Eg.: D:\Projects\FileUpload\build\web\Files\Temp\[someFilename.ext]
String tempPath = request.getRealPath("Files") + File.separator + "Temp" + File.separator + filename;
//Eg.: D:\Projects\FileUpload\build\web\Files\UploadedFiles\newFileName.txt
String newPath = request.getRealPath("Files") + File.separator + "UploadedFiles" + File.separator + "newFileName.txt";
//Writing the file into the above-mentioned path.
FileOutputStream fos = new FileOutputStream(tempPath);
InputStream ips = filePart.getInputStream();
byte[] data = new byte[ips.available()];
ips.read(data);
fos.write(data);
ips.close();
fos.close();
Renaming Logic
The code below moves the file from tempPath
to newPath
. The syntax for this is:
Files.move(Paths.get(oldPath), Paths.get(newPath));
. Attach this code below fos.close()
above.
Files.move(Paths.get(tempPath), Paths.get(newPath));
Conclusion
The code above writes the uploaded file to the UploadedFiles
Folder. The code above requires you to import following classes: javax.servlet.http.Part
, javax.servlet.annotation.MultipartConfig
, java.io.FileOutputStream
, java.io.InputStream
, java.nio.file.Files
and java.nio.file.Paths
and since it throws IOException and ServletException , the above block of code should be inside try...catch() block.