Upload file to JSP - how to change the default path for a downloaded file

I have two jps pages to handle uploading a single file. Here is the code to select the file:

 org.apache.commons.io.FilenameUtils, java.util.*, 
 java.io.File, java.lang.Exception" %>
...
 <form name="uploadFile" method="POST" action="processUpload.jsp"     
 enctype="multipart/form-data">
     <input type="file" name="myfile"><br />
     <input type="submit" value="Submit" />
 </form>
 ....

// -------- process the downloaded file ---------------------

<%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="org.apache.commons.fileupload.DiskFileUpload"%>
<%@ page import="org.apache.commons.fileupload.FileItem"%>
<%@ page import="java.util.List"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.io.File"%>


<%
    System.out.println("Content Type ="+request.getContentType());
    System.out.println("Cookies" + request.getCookies());

    DiskFileUpload fu = new DiskFileUpload();
    // If file size exceeds, a FileUploadException will be thrown
    fu.setSizeMax(1000000);

    List fileItems = fu.parseRequest(request);
    Iterator itr = fileItems.iterator();

    while(itr.hasNext()) {
      FileItem fi = (FileItem)itr.next();

      //Check if not form field so as to only handle the file inputs
      //else condition handles the submit button input
      if(!fi.isFormField()) {
        System.out.println("\nNAME: "+fi.getName());
        System.out.println("SIZE: "+fi.getSize());
        //System.out.println(fi.getOutputStream().toString());
        File fNew= new File(application.getRealPath("/"), fi.getName());

        System.out.println(fNew.getAbsolutePath());
        fi.write(fNew);
      }
      else {
        System.out.println("Field ="+fi.getFieldName());
      }
    }
 %>

This code puts the file in my build \ web folder. How to set the path to another directory on the server (provided that write permissions are set)? Thanks,

+3
source share
4 answers

Use the following code (adapted for user manual ):

// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(dir);

// Create a new file upload handler
DiskFileUpload upload = new DiskFileUpload(factory);

// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
+2
source

To set the file upload path:

<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File('/path/to/store/files'));
DiskFileUpload fu = new DiskFileUpload(factory);
0
source

? (JNI) - ( -Dpath =...) System.getProperty( "" ). , , System.getenv.

, , File.getTempFile. , - , , - , .

0

... - :

File newFile = new File(request.getSession().getServletContext().getRealPath("/someUploadDirectoryOnServer/"), multipartFile.getOriginalFilename());
-1
source

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


All Articles