如何确定多部分POST请求Java的文件大小?

时间:2018-04-09 08:05:35

标签: java rest

我想确定POST请求中文件的大小,然后再在后端处理它。考虑

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

我看到我可以使用Content-Disposition来获取文件大小。如何获取Content-Disposition标头以获取长度,或者是否应该有一个检查输入流大小的函数?

2 个答案:

答案 0 :(得分:1)

您可以使用@HeaderParam获取指定标头的值。

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

请注意,您仍然需要将文件大小添加到客户端的标头中,假设您正在使用类似DOM File API和fetch的内容。

答案 1 :(得分:0)

您应该计算缓冲区大小。

.... 
int size=0;

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