How to set a folder to store file downloads using Commons FileUpload

How to set file storage location on TOMCAT server?

I use commons.fileupload , and since it costs, I can store several .tmp files until catalina_base/temp , however my goal is to save the downloaded folders in their original form to d:\\dev\\uploadservlet\\web\\uploads

I know this question is vague, but to be honest, I have been working with servlets for such a short period of time, and I still do not understand the big picture, any suggestions on the code or links to textbooks would be very useful.

My servlet code that handles the downloads is as follows:

 package test; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.oreilly.servlet.MultipartRequest; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class TestServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final long MAX_UPLOAD_IN_MEGS = 5; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); //This is the folder I want to use!! //String uploadFolder = "d:\\dev\\uploadservlet\\web\\uploads"; boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); if (!isMultipartContent) { out.println("Upload unsuccessful<br/>"); return; } out.println("The following was uploaded:<br/>"); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAX_UPLOAD_IN_MEGS * 1024 * 1024); TestProgressListener testProgressListener = new TestProgressListener(); upload.setProgressListener(testProgressListener); HttpSession session = request.getSession(); session.setAttribute("testProgressListener", testProgressListener); try { List<FileItem> fields = upload.parseRequest(request); out.println("Number of fields: " + fields.size() + "<br/><br/>"); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { out.println("No fields found"); return; } out.println("<table border=\"1\">"); while (it.hasNext()) { out.println("<tr>"); FileItem fileItem = it.next(); boolean isFormField = fileItem.isFormField(); if (isFormField) { out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName() + "<br/>STRING: " + fileItem.getString() ); out.println("</td>"); } else { out.println("<td>file form field</td><td>FIELDNAME: " + fileItem.getFieldName() +// <br/>STRING: " + fileItem.getString() + "<br/>NAME: " + fileItem.getName() + "<br/>CONTENT TYPE: " + fileItem.getContentType() + "<br/>SIZE (BYTES): " + fileItem.getSize() + "<br/>TO STRING: " + fileItem.toString() ); out.println("</td>"); } out.println("</tr>"); } out.println("</table>"); } catch (FileUploadException e) { out.println("Error: " + e.getMessage()); e.printStackTrace(); } } } 

... and it gets the information from this HTML form:

 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Upload Page</title> <link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.8.24.custom.css"> <link rel="stylesheet" type="text/css" href="css/style.css" <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery-ui.js"></script> <script type="text/javascript" src="uploadFunctions.js"></script> </head> <body> <div> <form name="uploadForm" id="uploadForm" action="test" method="post" enctype="multipart/form-data"> <input type="hidden" name="hiddenfield1" value="ok"> <h3>Files to upload:</h3> <input type="file" size="50" name="file1"> <span id="file1Progress">-</span> <br/> <a href="javascript:previewFile(1)">Preview</a> <br/> <br/> <input type="file" size="50" name="file2"> <span id="file2Progress">-</span> <br/> <a href="javascript:previewFile(2)">Preview</a> <br/> <br/> <input type="file" size="50" name="file3"> <span id="file3Progress">-</span> <br/> <a href="javascript:previewFile(3)">Preview</a> <br/> <br/> <input type="file" size="50" name="file4"> <span id="file4Progress">-</span> <br/> <a href="javascript:previewFile(4)">Preview</a> <br/> <br/> <input type="file" size="50" name="file5"> <span id="file5Progress">-</span> <br/> <a href="javascript:previewFile(5)">Preview</a> <br/> <br/> <input type="button" value="Upload" id="submitButton" onclick="uploadForm.submit();doProgress();"> <br/> <br/> </form> <div class="progBar"> File number: <span id="fileText">-</span> is being uploaded.<br/> <br/> <progress id="progressBar" value="0" max="100"></progress><br/> Upload of all files is: <span id="progressText">-</span>% complete.<br/> </div> </div> </body> </html> 
+4
source share
3 answers

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.

+2
source

Have you seen javadoc DiskFileItemFactory ? There is a setRepository method that takes a File argument (the folder in which temporary files are stored).

So try the following:

  FileItemFactory factory = new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, new File("d:\\dev\\uploadservlet\\web\\uploads")); 

And when you process the form fields, you can save these files wherever you want.

Hope this helps you.

+2
source

You use FileUpload to control the download. therefore, in your code, you simply define the file and write data to it. I will copy only the relevant part and add to it:

 if (isFormField) { out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName() + "<br/>STRING: " + fileItem.getString() ); out.println("</td>"); } else { //write the file String myPath= ..... File f=new File(myPath); fileItem.write(f); out.println("<td>file form field</td><td>FIELDNAME: " + fileItem.getFieldName() +// <br/>STRING: " + fileItem.getString() + "<br/>NAME: " + fileItem.getName() + "<br/>CONTENT TYPE: " + fileItem.getContentType() + "<br/>SIZE (BYTES): " + fileItem.getSize() + "<br/>TO STRING: " + fileItem.toString() ); out.println("</td>"); } 

IMPORTANT: make sure that you have permission to write to the folder where you are writing the file.

0
source

Source: https://habr.com/ru/post/1447925/


All Articles