如下是springmvc中代码
@RequestMapping(value = "releasePro")
public String releasePro(@RequestParam(value = "file",required=false) MultipartFile file,Product product) throws IOException {
System.out.println("pro::"+product.getCsid()+","+product.getPname());
long startTime=System.currentTimeMillis();
System.out.println("fileName:"+file);
System.out.println("fileName:"+file.getOriginalFilename());
String path="D:/"+new Date().getTime()+file.getOriginalFilename();
File newFile=new File(path);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(newFile);
long endTime=System.currentTimeMillis();
System.out.println("方法二的运行时间:"+String.valueOf(endTime-startTime)+"ms");
return "releaseProOK";
}
下面是前端jsp
<form action="${pageContext.request.contextPath}/product/releasePro.do" method="post" enctype="multipart/form-data">
<div class="content">
<div class="form-group">
<label>图片文件</label>
<div style="clear: both"></div>
<span2><button type="button" id="newFile" class="mybutton" >上传图片</button></span2>
<span3 style="display:none">
<div class="file-box">
<input class="file-btn" id="file" name="file" type="file" multiple = "multiple" accept=".jpg" >
<button type="button" class="mybutton" >
<img height="35px" width="35px" src="${pageContext.request.contextPath}/images/timg.jpg">
</button>
</div>
</span3>
<div><span4 style="color:red;"></span4></div>
<span id="innerFile"></span>
<div style="clear: both"></div>
</div>
springmvc配置一下
<!-- 多部分文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>
最初写好出现的异常是HTTP Status 400 - Required CommonsMultipartFile[] parameter ‘XXX’ is not present
因为最初写成@RequestParam(value = “file”) 改成@RequestParam(value = “file”,required=false) 就好了,还有就是springmvc配置文件中的id一定要是multipartResolver不能改。
再有就是前端file文本域中的name也要与controller中注解保持一致@RequestParam(value = “file”,required=false)
最后就是空指针的问题,我的<input class="file-btn" id="file" name="file" type="file" multiple = "multiple" accept=".jpg" >
标签中写了两个name,而且两个name还不一样,导致空指针!