gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:23:58 26 4
gpt4 key购买 nike

我想在后端处理 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 header 来获取长度,或者是否应该有一个函数来检查输入流的大小?

最佳答案

您可以使用@HeaderParam来获取命名 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 {

请注意,假设您使用的是 DOM File API 和 fetch 等功能,您仍然需要将文件大小添加到客户端的 header 中。

关于java - 如何确定多部分POST请求Java的文件大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49728168/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com