I use following REST service (from this tutorial) to do file uploads from various number of clients to my GlassFish server, using jersey multipart implementation:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
@Path("/fileupload")
public class UploadFileService {
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "c://uploadedFiles/" + fileDetail.getFileName();
// save it
saveToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded via Jersey based RESTFul Webservice to: " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
// save uploaded file to new location
private void saveToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = null;
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This code works fine for me but I noticed following:
My questions are:
UPDATE 1
Attached the InputStream dump:
The strange thing here - .tmp file from screenshot is 0 bytes in size! The .tmp is deleted after out.close()
The uploaded file is probably either kept in memory (meaning it will be freed when the inputstream is clean up by the gc) or it is stored in the system default temp-folder. (Probably the same folder returned by System.getProperty("java.io.tmpdir")
, which means that it is cleaned up whenever you clean temporary files from your filesystem.
The exact location is dependent upon the framework which handles the restservices for you. In your case it appears to be jersey.
I don't know where jersey saves these files. You could try looking at the provided inputstream to see what type it is and where it's stored.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With