MultipartFile upload

今天在使用Spring MVC 进行文件上传时提示出如下错误:

 

java.lang.IllegalStateException: File has been moved - cannot be read again
at org.springframework.web.multipart.commons.CommonsMultipartFile.getBytes(CommonsMultipartFile.java:108) ~[spring-web-3.2.4.RELEASE.jar:3.2.4.RELEASE]
......

 在网上查了一下File has been moved - cannot be read again 错误都说将以下的maxInMemorySize改大就可以了。改了以后发现确实可以了,但是为什么呢?

 

 

    
    //允许最大可上传的文件大小
    
    //上传文件超出这个大小就会用于创建临时文件存储,而不使用内存存储
    

 其中三个参数如下所示:

 

/**
  * Set the maximum allowed size (in bytes) before uploads are refused. 
  * -1 indicates no limit (the default).
  * @param maxUploadSize the maximum upload size allowed 
  * @see org.apache.commons.fileupload.FileUploadBase#setSizeMax
  */
  public void setMaxUploadSize(long maxUploadSize) {
    this.fileUpload.setSizeMax(maxUploadSize);
  }
/**
  * Set the maximum allowed size (in bytes) before uploads are written to disk.
  * Uploaded files will still be received past this amount, but they will not be
  * stored in memory. Default is 10240, according to Commons FileUpload.
  * @param maxInMemorySize the maximum in memory size allowed
  * @see org.apache.commons.fileupload.disk.DiskFileItemFactory#setSizeThreshold
  */ 
  public void setMaxInMemorySize(int maxInMemorySize) {
        this.fileItemFactory.setSizeThreshold(maxInMemorySize);
  }

从以上内容可以分析出,实际进行修改maxInMemorySize并没有解决掉 File has been moved - cannot be read again问题,而是避开了这个问题。将文件流不再写入到临时文件,而是用内存存储。

 

以下留下我的解决办法不依赖maxInMemorySize,不过这个方法是根据业务而定的,首先要找到生成的临时文件被使用的地方,由于我的业务上先将MultipartFile写成了文件,然后又尝试用MultipartFile.getBytes()进行读取该文件类型,所以出现此问题,代码如下所示:

错误代码:

public String uploadFile(MultipartFile file,String filePath) {
   ....
   //创建原图
   file.transferTo(new File(filePath));
   // 图片上传 类型
   String fileType = readPictureType(file);
   ......
}

改正后代码:

public String uploadFile(MultipartFile file,String filePath) {
   ....
   // 图片上传 类型
   String fileType = readPictureType(file);
   //创建原图
   file.transferTo(new File(filePath));
  
   ......
}

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(Spring)