Just pass the desired location into FileItem#write()
method the usual way as described in the Apache Commons FileUpload's own users guide.
First initialize the upload folder in the init()
of your servlet.
private File uploadFolder;
@Override
public void init() throws ServletException {
uploadFolder = new File("D:\\dev\\uploadservlet\\web\\uploads");
}
(you can if necessary get this information from an environment variable or a properties file)
Then extract the base name and extension from the filename of the uploaded file and generate an unique filename based on it (you of course don't want that a previously uploaded file get overwritten when someone else by coincidence uploads a file with the same name, right?):
String fileName = FilenameUtils.getName(fileItem.getName());
String fileNamePrefix = FilenameUtils.getBaseName(fileName) + "_";
String fileNameSuffix = "." + FilenameUtils.getExtension(fileName);
File file = File.createTempFile(fileNamePrefix, fileNameSuffix, uploadFolder);
fileItem.write(file);
System.out.println("File successfully saved as " + file.getAbsolutePath());
// ...
(note that the File#createTempFile()
doesn't necessarily mean that it's a temporary file which will be auto-deleted at some time, no, it's in this particular case just been used as a tool in order to generate a file with a guaranteed unique filename in the given folder)
The FilenameUtils
is provided by Apache Commons IO which you should already have installed as it's a dependency of Commons FileUpload.
Note that you should absolutely not set it as 2nd argument of DiskFileItemFactory
constructor as suggested by the other answer. This represents, as clearly mentioned in its javadoc, the temporary disk file system location to store uploaded files when they exceed the threshold size (i.e. when they become too large to hold entirely in server's memory). This location is absolutely not intented as a permanent storage location for uploaded files. It will be auto-cleaned up at intervals by Commons FileUpload.