pom
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
spring-mvc添加配置
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
</beans>
Utils
/**
* 图片文件上传
*/
public Result<String> ImageUpload(MultipartFile file) {
Result<String> result = new Result<>();
String realPath = "d:\\files\\";
String path = "";
String savePaths = "";
if (file != null) {// 判断上传的文件是否为空
String type = null;// 文件类型
String fileName = file.getOriginalFilename();// 文件原名称
// 判断文件类型
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 trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
// 设置存放图片文件的路径
path = realPath + trueFileName;
System.out.println("存放图片文件的路径:" + path);
// 转存文件到指定的路径
try {
file.transferTo(new File(path));
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
savePaths = path;
result.setObj(savePaths);
} else {
System.out.println("Wrongtype");
result.setSuccess(false);
}
} else {
System.out.println("文件类型为空");
result.setSuccess(false);
}
}
return result;
}
请求代码:
@RequestMapping(value="insertExceptionPic",method=RequestMethod.POST)
@ApiOperation("上传异常图片")
@ResponseBody
public Result<String> uploadExceptionPicture(@RequestParam("file") MultipartFile file)
{
return utils.ImageUpload(file);
}
上传成功