1.添加pom依赖
<!-- 图片上传依赖 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2.在SpringMVC配置文件中配置文件解析器
<!-- 文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件最大的大小 -->
<property name="maxUploadSize" value="41300260"></property>
<!-- 字符编码 -->
<property name="defaultEncoding" value="utf-8"></property>
</bean>
3.创建上传文件控制器UploadController
@RestController
public class UploadController {
@PostMapping("/upload")
@PassToken
public ResponseResult upload(MultipartFile file, MultipartHttpServletRequest request) throws IOException {
Map data = null;
if(file != null){
String type = null;
String fileName=file.getOriginalFilename();
System.out.println("上传的源文件名称:"+fileName);
type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
if(type != null){
if("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())){
String realPath="D:\\develop\\tomcat\\apache-tomcat-8.5.40\\upload\\tmp_uploads\\";
String trueFileName=String.valueOf(System.currentTimeMillis())+fileName;
String tmpPath = "tmp_uploads/"+trueFileName;
String path=realPath+trueFileName;
System.out.println("图片存储的路径是:"+path);
file.transferTo(new File(path));
data = new HashMap<String,Object>();
data.put("tmp_path",tmpPath);
data.put("url","127.0.0.1:8090/"+tmpPath);
return new ResponseResult(data, 200, "上传成功");
}else {
return new ResponseResult(data, 500, "文件类型错误");
}
}else{
return new ResponseResult(data, 500, "文件类型为空");
}
}else{
return new ResponseResult(data, 500, "没有找到相对应的文件");
}
}
}