在网上搜了一下,找到很多代码都是使用推荐使用
采用spring提供的上传文件的方法
org.springframework.web.multipart.commons.CommonsMultipartResolver
赋值了一下代码直接使用
但是发现出现
Java.lang.ClassCastException: org.apache.catalina.connector.RequestFacade
cannot be cast to org.springframework.web.multipart.MultipartHttpServletRequest
就是在强制转换这里报错
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)getRequest();
最后改为
MultipartHttpServletRequest multiRequest = multipartResolver.resolveMultipart(getRequest());
并删除配置文件
<!-- <bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<value>32505856</value>上传文件大小限制为31M,31*1024*1024
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean> -->
获取文件成功
记录一下完整的controller:
@RequestMapping(value="/{token}",method=RequestMethod.POST)
@ResponseBody
public void upload() throws IllegalStateException, IOException {
//创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(getRequest().getSession().getServletContext());
//判断 request 是否有文件上传,即多部分请求
if(multipartResolver.isMultipart(getRequest())){
//转换成多部分request
/*MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)getRequest();*/
MultipartHttpServletRequest multiRequest = multipartResolver.resolveMultipart(getRequest());
//取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while(iter.hasNext()){
//记录上传过程起始时的时间,用来计算上传时间
int pre = (int) System.currentTimeMillis();
//取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if(file != null){
//取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
//如果名称不为“”,说明该文件存在,否则说明该文件不存在
if(myFileName.trim() !=""){
System.out.println(myFileName);
//重命名上传后的文件名
String fileName = "demoUpload" + file.getOriginalFilename();
//定义上传路径
String path = "D:/upload" + fileName;
File localFile = new File(path);
file.transferTo(localFile);
}
}
//记录上传该文件后的时间
int finaltime = (int) System.currentTimeMillis();
System.out.println(finaltime - pre);
}
}
}
完整的jsp
<body>
<h1>springMVC包装类上传文件</h1>
<form name="formUpload" action="days/${token }" enctype="multipart/form-data" method="post" id="test">
<div id="newUpload2">
<input type="file" name="file">
</div>
<input type="text" name="test" >
<input type="submit" value="上传" >
</form>
</body>