如何从org.springframework.web.multipart.MultipartFile
找到正确的文件大小
double bytes = m.getSize();
double kilobytes = (bytes / 1024);
double megabytes = (kilobytes / 1024);
System.out.println(megabytes);
但它没有给出正确的尺寸。
此处m.getSize()
返回2264855,但使用此方法它给出的文件大小约为2MB,但我的文件系统中的实际大小为8MB
private HashMap add(@RequestParam( value = "files", required = false) MultipartFile[] mPartFile){
if(mPartFile != null && mPartFile.length>0){
for(MultipartFile m:mPartFile){
if(!CoreServices.isSupportedFile(m.getContentType())){
hm.put("status", MConstants.OPERATION_FAILED);
hm.put("reason", "File: "+m.getOriginalFilename()+" is not supported. Upload only jpeg, png, gif image files.");
return hm;
}
long size = m.getSize();
if( size> MConstants.MAX_ALLOWED_FILE_SIZE){
hm.put("status", MConstants.OPERATION_FAILED);
hm.put("reason", "File: "+m.getName()+" is not acceptable, its size is more than 5MB.");
return hm;
}
}
}
}
此处,5MB 限制的 MAX_ALLOWED_FILE_SIZE
值为 5000000
最佳答案
您正在使用 MultipartFile 的方法 getSize()
,我认为该方法以二进制形式返回字节大小。
因此,将其转换为 MB 时,您必须将 file.getSize()
与 0.00000095367432
相乘。这将为您提供以 MB 为单位的大小。您可以验证here .
我也在用这个。我可以看到 Windows 中文件的大小为 18.9 KB,这是实际大小而不是磁盘上的大小。就我而言,我需要以 KB 为单位的信息,因此我将其乘以 0.0009765625,结果返回 18.9462890625 KB,这接近文件的大小,可能是 Windows 将其四舍五入。
我相信将 file.getSize()
与 0.00000095367432
相乘会起作用。
关于spring - 从 Spring MultipartFile 获取正确的文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27175729/