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);
Author by
Thunder Dragon
Android developer & photography enthusiast.
Updated on November 21, 2022Comments
-
Thunder Dragon over 1 year
How do I convert an uploaded file from apache's
UploadedFile
class to ajava.io.File
class? -
Thunder Dragon over 12 yearserror shown in the following line- while(length = reader.read(buffer, position, partition)) Type mismatch: cannot convert from int to boolean
-
Bahadir Tasdemir over 8 yearsTried this method but copied file was broken. System said "cannot open file".