添加jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
配置在spring配置文件中配置bean
<!-- SpringMVC上传文件时,需配置MultipartResolver处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 指定所上传文件的总大小不能超过80M......注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="80000000"/>
</bean>
<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
</props>
</property>
</bean>
java后台
@RequestMapping("/addImagerToService")
@ResponseBody
private void addImgFileTO(HttpServletRequest request){
MultipartFile file=((MultipartHttpServletRequest) request).getFile("file");
if(file!=null){
manageImageService.addImgFileTO(file);
};
}
service
@Override
public void addImgFileTO(MultipartFile file) {
long id = NumberUtil.getLong(ReportNumberUtil.generateId());
String realname = file.getOriginalFilename();
String type = realname.substring(realname.indexOf("."));
realname = realname.substring(0,realname.indexOf("."));
type = type.toLowerCase();
String filePath=ManageImageServiceImpl.IMGFILEPATH+File.separator+realname+type;//文件路径要包含文件名称
File newF = new File(filePath);
try {
InputStream input = file.getInputStream();
FileUtils.copyInputStreamToFile(input, newF);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
html
<input class="inputFileHiden filePosition" multiple type="file" onchange="UpladFile()" />
function UpladFile() {
var files = $("#imgForm").find("input")[0].files[0]; // 获取文件对象
var FileController = ctp + '/imageAction/addImagerTo.action'; // 接收上传文件的后台地址
// FormData 对象
var form = new FormData();
form.append("file", files); // 文件对象
// XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
xhr.open("post", FileController, true);
xhr.onload = function () {
alert("上传完成!");
};
xhr.send(form);
}