首先需要引入jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
其次需要在配置文件中加入bean的申明
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置默认编码 -->
<property name="defaultEncoding" value="utf-8"></property>
<!-- 上传图片最大大小5M-->
<property name="maxUploadSize" value="10484880"></property>
</bean>
controller代码
public ResultBody upFile(MultipartFile[] uploadFile) throws Exception {
String filePath = SCMConfigUtil.getInstance().getProperty("workerSrc", "");
if (filePath.equals("")) {
return ResultBody.success("scm 配置错误");
}
// 生成文件
filePath = filePath.substring(0, filePath.lastIndexOf('/'));
for (MultipartFile uploadFiles : uploadFile) {
//获取上传文件的名称
String fileName = uploadFiles.getOriginalFilename();
String path = filePath + File.separator + fileName;
File file = new File(path);
if (file.exists()) {
file.delete();
}
uploadFiles.transferTo(file);
}
}
前端页面代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试上传与下载</title>
</head>
<body>
<a href="down">down</a>
<form action="/mgr/upFile" method="post" enctype="multipart/form-data">
头像 :<input type="file" multiple="multiple" name="uploadFile">
<input type="submit" value="上传">
</form>
</body>
</html>