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:
- first the file is uploaded somewhere in the server
- the method uploadFile(...) is triggered with an InputStream to the uploaded file, so I can make a copy of it in desired location using saveToFile(...)
My questions are:
- where is the file (see (1) above) initially stored?
- How to delete the uploaded file to free resources?
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()