gpt4 book ai didi

java - Spring HTTP 文件上传 : Validation of File Size

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:37:05 25 4
gpt4 key购买 nike

我有一个关于在基于 Spring 的 HTTP 文件上传服务中验证文件大小的基本问题。我正在使用 Spring 的 org.springframework.web.multipart.MultipartFile 来执行文件上传。

我的问题是 multipartFile.getSize() 方法是否仅在整个上传完成后才返回大小?如果是,根据大小限制文件的正确前瞻性方法是什么?

Note: The reason I ask this question is because I do not want an end user to upload 1 GB file and get an error message after an hour saying, "Sorry, maximum file size allowed is 2 KB."

最佳答案

第一个问题的答案是,multipartFile.getSize() 方法是否仅在整个上传完成后才返回大小?

-不,您会在整个上传完成之前获得 multipartFile.getSize()。

@RequestMapping(value = "/CSVfileupload")
public @ResponseBody String callCSVFileUpload(
@RequestParam("CSVfilepath") MultipartFile multipartFile, HttpSession session,HttpServletRequest request) throws IOException {
//get the file size before doing any operation
logger.info("Controller - callCSVFileUpload() multipartFile.getSize()="+ multipartFile.getSize());
InputStream inputStream = new BufferedInputStream(multipartFile.getInputStream());
JsonArray response=null;
try{
//you business logic
}
catch(Exception e){
e.printStackTrace();
}
logger.info(" response.toString()="+ response.toString());
return response.toString();
}//end of callCSVFileUpload

您可以在 application-context.xml 文件中使用 CommonsMultipartResolver。

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="50000000" />
</bean>

关于java - Spring HTTP 文件上传 : Validation of File Size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40169921/

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