Java 基于spring框架 使用 MultipartFile 及 File实现文件上传功能
Controller
/**
* 上传文件
*/
@RequestMapping("uploadFile")
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()){
logger.info("文件不存在");
return "文件不存在";
}
String stase = UploadFile.UploadFile(file);
return stase;
}
Service
/**
* 文件上传实现逻辑
*/
@Service
public class UploadFileImpl implements UploadFile {
private static Logger logger = Logger.getLogger(UploadFileImpl.class);
private static String StatesSuccess = "200";
private static String StatesFailed = "500";
@Override
public String UploadFile(MultipartFile file) {
logger.info("上传文件开始");
String originalFilename = file.getOriginalFilename();
String contentType = file.getContentType();
String name = file.getName();
logger.info("文件名为:"+originalFilename+"类型为:"+contentType);
Resource resource = file.getResource();
//重新定义文件名
long l = System.currentTimeMillis();
//重新修正文件名
String fileNames = l + "." + originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
//定义保存路径
String uploadDesk = "F:\\sc\\cscs\\";
File file1 = new File(uploadDesk + fileNames);
if (!file1.getParentFile().exists()) {
file1.getParentFile().mkdirs();
}
try {
file.transferTo(file1);
logger.info("文件上传成功");
return StatesSuccess;
} catch (IOException e) {
e.printStackTrace();
logger.error("文件上传失败");
return StatesFailed;
}
}
}