[英]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. 我想确定POST请求中文件的大小,然后再在后端中对其进行处理。 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. 我看到我可以使用Content-Disposition来获取文件大小。 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? 如何获取Content-Disposition标头以获取长度,还是应该有一个检查输入流大小的函数?
You can use @HeaderParam
to get the value of a named header. 您可以使用@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 {
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. 请注意,假设您正在使用DOM File API和fetch之类的内容,则仍然需要在客户端的标头中添加文件大小。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.