说明:
1、SpringMVC实现文件上传,需要再添加两个jar包。一个是文件上传的jar包,一个是其所依赖的IO包。这两个jar包
commons-fileupload-1.2.2.jar
commons-io-2.4.jar
Controller
@ResponseBody
@RequestMapping("uploadfile")
public BEI uploadfile(HttpServletRequest request,@RequestParam("file") MultipartFile file,@RequestParam("name") String name)
throws Exception
{
//获取整个文件名字包括后缀
System.out.println(file.getOriginalFilename());
String path = request.getServletContext().getRealPath("/static/img");
File newfile=new File(path+File.separator +
name+"."+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1));
file.transferTo(newfile);
return BEI.ok();
}
form
method="post" enctype="multipart/form-data" (重点,文件上传必须为post,enctype="multipart/form-data":将表单中的数据变成二进制数据进行上传)
<form action="/TBS/worker/uploadfile" method="post" enctype="multipart/form-data">
<input type="text" name="name">
<input type="file" name="file">
<input type="submit" value="提交">
</form>
Spring配置文件加入:
<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<!-- 上传文件大小限制为31M,31*1024*1024 -->
<value>32505856</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>