How to get file size in rest api jersey

I did rest api in this, it works fine, but I want to read the file size, and I used below code to read the file size

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

but I got a file size of -1.

Can anyone suggest me how I can read the actual file size.

But using

System.out.println(" data name ="+ filePart.getContentDisposition().getFileName());

I got the correct file name.

+4
source share
2 answers

Hope this is what you wanted. I tested it on my system. This displays the file size in bytes.

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

make sure you have the following dependency in your pom.xml

<dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
        <version>2.13</version>
</dependency>

, . , .

super(YourClass.class, MultiPartFeature.class);
0

HttpServletRequest. , .

   @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response putFile(@Context HttpServletRequest request){
      Part part = request.getPart("filename");
      long fileSize = part.getSize();
    }
0

All Articles