从Spring MultipartFile获取正确的文件大小

时间:2014-11-27 16:59:19

标签: spring spring-mvc

如何从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;                
            }            
        }
    }
}

此处MAX_ALLOWED_FILE_SIZE的值为5000000,限制为5MB

1 个答案:

答案 0 :(得分:1)

您正在使用MultipartFile的方法getSize(),我认为该方法以二进制形式返回字节大小。
因此,要将其转换为MB,您必须将file.getSize()0.00000095367432相乘。这将为您提供MB大小。您可以验证here

我正在使用相同的。我可以看到Windows中文件的大小为18.9 KB,这是实际大小,而不是磁盘上的大小。就我而言,我需要以KB为单位的信息,因此我将其乘以0.0009765625,并返回18.9462890625 KB,该值接近文件的大小,可能是Windows正在对其进行舍入。

我相信将file.getSize()0.00000095367432相乘会有效。