packagecn.jiashubing.controller;importcn.jiashubing.common.StringConstants;importcn.jiashubing.result.ResultModel;importio.swagger.annotations.Api;importio.swagger.annotations.ApiOperation;importio.swagger.annotations.ApiParam;importorg.springframework.util.ResourceUtils;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;importorg.springframework.web.multipart.MultipartFile;import java.io.*;importjava.text.SimpleDateFormat;importjava.util.Date;/***@authorjiashubing
*@since2019/6/25*/@RestController
@Api(tags= "稿件")
@RequestMapping(value=StringConstants.API)public classArticleController {
@ApiOperation("上传附件")
@RequestMapping(value= "/uploadFile", method =RequestMethod.POST)public ResultModel uploadFile(@RequestParam("file") @ApiParam(value = "二进制文件流") MultipartFile file) {
String fileName= file.getOriginalFilename();//获取文件名
fileName =getFileName(fileName);
String filepath=getUploadPath();if (!file.isEmpty()) {try (BufferedOutputStream out = newBufferedOutputStream(new FileOutputStream(new File(filepath + File.separator +fileName)))) {
out.write(file.getBytes());
out.flush();return new ResultModel<>(fileName);
}catch(FileNotFoundException e) {return new ResultModel<>(false, "上传文件失败 FileNotFoundException:" +e.getMessage());
}catch(IOException e) {return new ResultModel<>(false, "上传文件失败 IOException:" +e.getMessage());
}
}else{return new ResultModel<>(false, "上传文件失败,文件为空");
}
}/*** 文件名后缀前添加一个时间戳*/
privateString getFileName(String fileName) {int index = fileName.lastIndexOf(".");final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss"); //设置时间格式
String nowTimeStr = sDateFormate.format(new Date()); //当前时间
fileName = fileName.substring(0, index) + "_" + nowTimeStr +fileName.substring(index);returnfileName;
}/*** 获取当前系统路径*/
privateString getUploadPath() {
File path= null;try{
path= new File(ResourceUtils.getURL("classpath:").getPath());
}catch(FileNotFoundException e) {
e.printStackTrace();
}if (!path.exists()) path = new File("");
File upload= new File(path.getAbsolutePath(), "static/upload/");if (!upload.exists()) upload.mkdirs();returnupload.getAbsolutePath();
}
}