//获取到了xxx在webapp下真实的路径
String path =request.getSession().getServletContextPath().getRealPath("xxx");
file.exist(); 存在为true 不存在为false
file.mkdirs();
//spring-mvc.xml
<!--文件上传-->
<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>
<!--文件上传-->
//FileUploadController
@RequestMapping("upload")
@ResponseBody
public Object upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
// 获取服务端webapp下真实路径
String path = request.getSession().getServletContext().getRealPath("upload");
Date currentDate = new Date();
// 文件夹日期格式
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
File fileDir = new File(path, dateFormat.format(currentDate));
// 获取文件类型
String originalFilename = file.getOriginalFilename();
String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
// 文件名
String fileName = Long.toString(currentDate.getTime()) + fileType;
File targetFile = new File(fileDir, fileName);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
try {
if(!targetFile.exists())file.transferTo(targetFile);
} catch (IOException e) {
e.printStackTrace();
return new Ret.Builder(RetCode.ERROR).msg("上传失败");
}
return new Ret.Builder(RetCode.SUCCESS).msg("上传成功");
}
}