---
title: "MultipartFile upload"
author: "TimerBin"
date: "2015-04-07T12:48:53Z"
tags: []
categories: ["开源软件"]
slug: "multipartfile-upload"
draft: false
lastmod: "2015-04-07T12:48:53Z"
id: 2199920
url: "https://timerbin.iteye.com/blog/2199920"
---

今天在使用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改大就可以了。改了以后发现确实可以了，但是为什么呢？

 

 

```
<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    <property name="defaultEncoding" value="utf-8"></property>
    //允许最大可上传的文件大小
    <property name="maxUploadSize" value="10485760000"></property>
    //上传文件超出这个大小就会用于创建临时文件存储，而不使用内存存储
    <property name="maxInMemorySize" value="4194304"></property>
</bean>
```

 其中三个参数如下所示：

 

```
/**
  * 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));
  
   ......
}
```