SpringBoot之文件上传

时间:2023-03-08 16:01:49
 package org.springboot.controller;

 import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springboot.constant.Constant;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import java.io.File;
import java.io.IOException; /**
* @Auther:GongXingRui
* @Date:2018/12/25
* @Description: 文件下载
**/
@Controller
public class FileUpload {
Logger logger = LogManager.getLogger(FileUpload.class); @GetMapping("/upload")
public String upload() {
return "upload";
} @PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "上传失败,请选择文件";
} String fileName = file.getOriginalFilename();
// String filePath = "C:/Temp/upload";
String filePath = Constant.CONFIG_PROPERTIES.getProperty("upload.path");
File dest = new File(filePath + File.separator + fileName);
//判断文件是否已经存在
if (dest.exists()) {
logger.info("文件已经存在 -> " + dest.getPath());
}
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
logger.info("目录不存在,自动创建 -> " + dest.getParentFile().getPath());
}
try {
file.transferTo(dest);
logger.info("上传成功");
return "上传成功";
} catch (IOException e) {
logger.error(e.toString(), e);
}
return "上传失败!";
}
}