使用Jersey 2通过流媒体上传文件

时间:2014-07-11 18:41:49

标签: java rest jersey streaming

我正在尝试使用Jersey创建文件上传API。我想获得有关服务器端上传进度的详细信息(可能吗?)。在网上搜索,建议是使用流来传输文件。但是......甚至在下面描述过,服务器只是执行" putFile"文件到达后的方法。另一个问题是,当我尝试大于40mb的文件

时,这些代码仅适用于小文件
@Path("/file")
public class LargeUpload {

private static final String SERVER_UPLOAD_LOCATION_FOLDER = "/Users/diego/Documents/uploads/";

@PUT
@Path("/upload/{attachmentName}")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response putFile(@PathParam("attachmentName") String attachmentName,
                         InputStream fileInputStream) throws Throwable {

    String filePath = SERVER_UPLOAD_LOCATION_FOLDER + attachmentName;

    saveFile(fileInputStream, filePath);

    String output = "File saved to server location : ";

    return Response.status(200).entity(output).build();

}


// save uploaded file to a defined location on the server
private void saveFile(InputStream uploadedInputStream, String serverLocation) {

    try {
        OutputStream outpuStream = new FileOutputStream(new File(
                serverLocation));
        int read = 0;
        byte[] bytes = new byte[1024];

        outpuStream = new FileOutputStream(new File(serverLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            outpuStream.write(bytes, 0, read);
        }
        outpuStream.flush();
        outpuStream.close();
    } catch (IOException e) {

        e.printStackTrace();
    }

}

public static void main(String[] args) throws FileNotFoundException {

    ClientConfig config = new ClientConfig();
    config.property(ClientProperties.CHUNKED_ENCODING_SIZE, 1024);

    Client client = ClientBuilder.newClient(config);
    File fileName = new File("/Users/diego/Movies/ff.mp4");
    InputStream fileInStream = new FileInputStream(fileName);
    String sContentDisposition = "attachment; filename=\"" + fileName.getName()+"\"";

    Response response = client.target("http://localhost:8080").path("upload-controller/webapi/file/upload/"+fileName.getName()).
            request(MediaType.APPLICATION_OCTET_STREAM).header("Content-Disposition", sContentDisposition).
            put(Entity.entity(fileInStream, MediaType.APPLICATION_OCTET_STREAM));

    System.out.println(response);

}

0 个答案:

没有答案