質問

I am using REST API with JAX-RS,

I just upload the file and my server code is as follows,

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
@Path("/upload")
public String uploadFunction(@Context UriInfo uriInfo,
        @FormDataParam("upload") final InputStream inputStream,
        @FormDataParam("upload") final FormDataContentDisposition fileDetail) {
//Here I want to get the actual file. For eg: If i upload a myFile.txt. I need to get it as myFile.txt here
 }

My code is working correctly when I parse the content of the file using inputStream and performed some operation. Now I want the exact file. Since I need to send mail with the actual file attached

Here I want to get the actual file. For eg: If i upload a myFile.txt. I need to get it as myFile.txt here. How can I achieve it?

役に立ちましたか?

解決

I might be wrong here, but when using the InputStream you can only get the inputstream, because the file is not stored on the server yet.

So in that case you should be able to do something like the following:

private static final String SERVER_UPLOAD_LOCATION_FOLDER = "/somepath/tmp/uploaded_files/";

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
@Path("/upload")
public String uploadFunction(@Context UriInfo uriInfo,
        @FormDataParam("upload") final InputStream inputStream,
        @FormDataParam("upload") final FormDataContentDisposition fileDetail) {

        String filePath = SERVER_UPLOAD_LOCATION_FOLDER + fileDetail.getFileName();
        // save the file to the server
        saveFile(inputStream, filePath);
        String output = "File saved to server location : " + filePath;
        return Response.status(200).entity(output).build();  
}

private void saveFile(InputStream uploadedInputStream, String serverLocation) {
    try {
        OutputStream outputStream = new FileOutputStream(new File(serverLocation));
        int read = 0;
        byte[] bytes = new byte[1024];
        outputStream = new FileOutputStream(new File(serverLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
        outputStream.flush();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top