如何在服务器端获取实际上传的文件?

时间:2014-01-22 09:59:30

标签: java rest jersey jax-rs multipartform-data

我正在使用REST API和JAX-RS,

我只是上传文件,我的服务器代码如下,

@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
 }

当我使用inputStream解析文件的内容并执行某些操作时,我的代码正常工作。现在我想要确切的文件。因为我需要发送附有实际文件的邮件

这里我想获得实际文件。例如:如果我上传myFile.txt。我需要在这里将它作为myFile.txt。我怎样才能实现它?

1 个答案:

答案 0 :(得分:2)

我可能在这里错了,但是在使用InputStream时你只能获得输入流,因为该文件尚未存储在服务器上。

因此,在这种情况下,您应该能够执行以下操作:

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();
    }
}