Just pass the desired location to FileItem#write() usual way, as described in the Apache Commons FileUpload user guide .
Initialize the download folder in the init() your servlet.
private File uploadFolder; @Override public void init() throws ServletException { uploadFolder = new File("D:\\dev\\uploadservlet\\web\\uploads"); }
(if necessary, you can get this information from an environment variable or properties file)
Then extract the base name and extension from the file name of the downloaded file and create a unique file name based on it (you, of course, do not want the previously downloaded file to be overwritten when someone coincidentally downloaded the file using 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 File#createTempFile() does not necessarily mean that this is a temporary file that will be automatically deleted for some time, no, in this particular case it was used only as a tool to create a file with a guaranteed unique file name in this folder )
FilenameUtils provided by Apache Commons IO, which you should already install, because it depends on Commons FileUpload.
Note that you absolutely must not set it as the 2nd argument to the DiskFileItemFactory constructor, as suggested by another answer. This, as its javadoc clearly states, is the temporary location of the disk file system for storing downloaded files when they exceed the threshold size (i.e. when they become too large to completely hold the server’s memory). This place is absolutely not intended as a permanent place to store downloaded files. It will be automatically cleaned using Commons FileUpload.
source share