1、(Maven)在pom.xml上添加两个依赖包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
2、在springmvc的配置文件添加
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600"/>
</bean>
注意maxuploadsize是用来限制文件大小的,如果该值设置得太小,又传了一个很大的图片就会报错
2、修改前端提交方式为:
<form method="post" enctype="multipart/form-data">
<div>
<div>
<input type="file" name="image">
</div>
<button type="submit">Submit</button>
</form>
3、在监听的方法上使用此传入参数:
@RequestParam(value="image",required=false)MultipartFile image
,value对应前端的name值
4、把MultipartFile转换成File
第一种方法:
MultipartFile file = xxx;
CommonsMultipartFile cf= (CommonsMultipartFile)file;
DiskFileItem fi = (DiskFileItem)cf.getFileItem();
File f = fi.getStoreLocation();
会在项目的根目录的临时文件夹下生成一个文件;
第二种方法:
transferTo(File dest);
会在项目中生成一个新文件;
第三种方法:
File f = (File) xxx 强转即可。前提是要配置multipartResolver,要不然会报类型转换失败的异常。
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600"/>
<property name="maxInMemorySize" value="4096"/>
</bean>
第四种方法:
Workbook wb = Workbook.getWorkbook(xxx .getInputStream());
转换为输入流,直接读取;
第五种方法:
byte[] buffer = myfile.getBytes();
先转换为字节数组,没试过;
参考:
http://www.cnblogs.com/wmmang-blog/p/3705268.html
http://www.cnblogs.com/hahaxiaoyu/p/5102900.html