How to get java.io.File from Apache's UploadedFile class?

10,785

Solution 1

Looking at the documentation (UploadedFile and File) for both classes, here's one solution.

Since you can access the InputStream of the UploadedFile, you can read in the data of the uploaded file and write it to a temporary location or another location that your application can manage.

// assume that you have the UploadedFile object named uploadedFile
InputStreamReader reader = new InputStreamReader(uploadedFile.getInputStream());
int partition = 1024;
int length = 0;
int position = 0;
char[] buffer = new char[partition];
FileWriter fstream = new FileWriter("out.tmp");
do{
    length = reader.read(buffer, position, partition)
    fstream.write(buffer, position, length);
}while(length > 0);
File file = new File("out.tmp");

Solution 2

The easiest way is to use apache commons FileUtils .

File destFile= new File("somefile.txt");
FileUtils.copyInputStreamToFile(uploadedFile.getInputStream(), destFile);
Share:
10,785
Thunder Dragon
Author by

Thunder Dragon

Android developer & photography enthusiast.

Updated on November 21, 2022

Comments

  • Thunder Dragon
    Thunder Dragon over 1 year

    How do I convert an uploaded file from apache's UploadedFile class to a java.io.File class?

  • Thunder Dragon
    Thunder Dragon over 12 years
    error shown in the following line- while(length = reader.read(buffer, position, partition)) Type mismatch: cannot convert from int to boolean
  • Bahadir Tasdemir
    Bahadir Tasdemir over 8 years
    Tried this method but copied file was broken. System said "cannot open file".