首先需要引入两个jar包:
springmvc.xml中配置关键bean:
配置CommonsMultipartResolver,用于实现文件上传 id值不能乱起
springIOC容器在初始化时,会自动寻找一个Id="multipartResolver"的bean,并将其加入ioc容器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<!--上传单个文件的最大值,单位Byte,如果-1代表无限值-->
<property name="maxUploadSize" value="-1"></property>
</bean>
实例:
前台代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form method="post" action="handler/download" enctype="multipart/form-data">
描述:<input type="text" name="des" placeholder="请输入描述信息" /><br/>
上传的文件:<input type="file" name="file" /><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
后台逻辑代码:
package handler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@Controller
@RequestMapping("handler")
public class control {
@RequestMapping("download")
public String testUpload(@RequestParam("des") String des, @RequestParam("file") MultipartFile file) throws IOException {
System.out.println("文件描述信息"+des+", 文件名为:"+file.getOriginalFilename() + " 简称:"+file.getName());
InputStream input = file.getInputStream();
OutputStream output = new FileOutputStream("G:\\IDEA\\Myweb\\Ajax-delete\\web\\upload\\"+file.getOriginalFilename());
byte[] bs = new byte[1024];
int len = -1;
while((len=input.read(bs))!=-1){
output.write(bs,0,len);
}
output.close();
input.close();
System.out.println("上传成功!!!");
return "success";
}
}