如何获取rest api jersey中的文件大小

Anu*_*man 5 java rest multipartform-data jersey

我做了一个rest api,它工作正常,但我想读取文件的大小,我使用下面的代码来读取文件的大小

@POST
@Path("/test")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload( FormDataMultiPart form ){
    System.out.println(" size of file="+ filePart.getContentDisposition().getSize());
}
Run Code Online (Sandbox Code Playgroud)

但我得到了文件 -1 的大小。

任何人都可以建议我如何读取文件的实际大小。

但是使用

System.out.println(" data name ="+ filePart.getContentDisposition().getFileName());
Run Code Online (Sandbox Code Playgroud)

我得到了正确的文件名。

Abh*_*hek 1

希望这是您想要的。我已经在我的系统中验证过了。这将打印文件的大小(以字节为单位)。

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) {

    String uploadedFileLocation = "/home/Desktop/" + fileDetail.getFileName();
    // save it
    writeToFile(uploadedInputStream, uploadedFileLocation);
    File file = new File(uploadedFileLocation);
    System.out.println(file.length() + " in bytes");
    String output = "File uploaded to : " + uploadedFileLocation;
    return Response.status(200).entity(output).build();
}

// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {

    try {
        OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
        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();
    }
}
Run Code Online (Sandbox Code Playgroud)

确保您的 pom.xml 中有以下依赖项

<dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
        <version>2.13</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

还将其添加到扩展资源配置的应用程序类中。这会将您的球衣课程注册为具有多部分内容。

super(YourClass.class, MultiPartFeature.class);
Run Code Online (Sandbox Code Playgroud)

  • 使用您的解决方案,您必须先将流写入文件,然后才能确定大小。这里的挑战当然是在必须遍历整个流之前知道上传的大小。 (5认同)