1.添加jar包
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISM3MDMxQDN4EjMxATM2EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
2.spring-controller.xml配置:
<!-- 文件上传解析器配置以及大小编码等参数 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10485760000" />
<property name="maxInMemorySize" value="40960" />
</bean>
3.控制层代码:
1.单文件上传:
@RequestMapping("upload")
@ResponseBody
public void upload(@RequestParam("file") CommonsMultipartFile file,HttpSession session)throws Exception {
System.out.println("filename------->"+file.getOriginalFilename());
if(!file.isEmpty()){
try {
String filename = new Date().getTime()+file.getOriginalFilename();
String realPath = session.getServletContext().getRealPath("/WEB-INF/upload/");
FileOutputStream os = new FileOutputStream(realPath + filename);
InputStream in = file.getInputStream();
int b = ;
while((b=in.read()) != -){
os.write(b);
}
os.flush();
os.close();
in.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.多文件上传:
@RequestMapping("threeFileupload")
public String threeFileUpload(
@RequestParam("file") CommonsMultipartFile files[],
HttpSession session) {
List<String> list = new ArrayList<String>();
// 获得项目的路径
String path = session.getServletContext().getRealPath(
"/WEB-INF/upload/");
// 上传位置
File f = new File(path);
if (!f.exists())
f.mkdirs();
for (int i = ; i < files.length; i++) {
// 获得原始文件名
String fileName = files[i].getOriginalFilename();
System.out.println("原始文件名:" + fileName);
// 新文件名
String newFileName = new Date().getTime()
+ files[i].getOriginalFilename();
if (!files[i].isEmpty()) {
try {
FileOutputStream fos = new FileOutputStream(path
+ newFileName);
InputStream in = files[i].getInputStream();
int b = ;
while ((b = in.read()) != -) {
fos.write(b);
}
fos.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("上传文件到:" + path + newFileName);
list.add(path + newFileName);
}
HashMap map =new HashMap();
map.put("content", list);
map.put("code",);
map.put("msg", "OK");
return Tools.getJson(map);
}
这样一个基于框架的简单的上传文件功能就好啦!