A.Dumas
A.Dumas

Reputation: 3267

How to determine the file size for multi-part POST request Java?

I want to determine the size of a file in a POST request before it is processed in my backend. Consider

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
        @FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail) throws IOException {
         String uploadedFileLocation = "somePath" + fileDetail.getFileName();
        // save it
    writeToFile(uploadedInputStream, uploadedFileLocation);
    String output = "File uploaded to : " + uploadedFileLocation;
    return Response.ok(output).build();
}

// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) throws IOException {
    int read;
    final int BUFFER_LENGTH = 1024;
    final byte[] buffer = new byte[BUFFER_LENGTH];
    OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
    while ((read = uploadedInputStream.read(buffer)) != -1) {
        out.write(buffer, 0, read);
    }
    out.flush();
    out.close();
}

I saw I can use the Content-Disposition to get the file size. how can I get the Content-Disposition header to get the length or should there be a function that checks the size of the input stream?

Upvotes: 0

Views: 1739

Answers (2)

cbr
cbr

Reputation: 13652

You can use @HeaderParam to get the value of a named header.

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
    @FormDataParam("file") InputStream uploadedInputStream,
    @FormDataParam("file") FormDataContentDisposition fileDetail,
    @HeaderParam("Content-Disposition") String contentDisposition
) throws IOException { 

Note that you still need to add the file size to the header in the client side, assuming you're using something like the DOM File API and fetch.

Upvotes: 1

Abdullah G
Abdullah G

Reputation: 157

You should count buffer size.

.... 
int size=0;

while ((read = uploadedInputStream.read(buffer)) != -1) {
    out.write(buffer, 0, read);
    size += read.length;
}
System.out.println("size : "+size);

Upvotes: 0

Related Questions