Spring Boot 06 -- 文件上传
2019-08-20 本文已影响0人
半碗鱼汤
一、说明
给工程添加一个文件上传接口
二、controller
@Autowired
private ITestService testService;
@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam(value = "file") MultipartFile file) {
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
return testService.upload(file);
}
三、service
String upload(MultipartFile file);
四、service impl
private static final Logger logger = LoggerFactory.getLogger(TestServiceImpl.class);
@Value("${file.upload.path}")
private String uploadPath;
@Override
public String upload(MultipartFile file) {
String fileName = file.getOriginalFilename();
String filePath = uploadPath;
File dest = new File(filePath);
// 判断文件夹是否存在
if (dest.isDirectory()) {
logger.info("文件夹存在");
} else {
logger.info("文件夹不存在,正在创建...");
dest.mkdirs();
logger.info("文件夹创建成功");
}
dest = new File(filePath + fileName);
//判断文件是否存在
if (dest.exists()) {
logger.info("文件已存在,覆盖之...");
}
try {
file.transferTo(dest);
logger.info("上传成功");
logger.info("上传文件路径为:" + filePath + fileName);
return filePath + fileName;
} catch (IOException e) {
logger.error(e.toString(), e);
}
return "上传失败!";
}