Controller层
@RestController
@RequestMapping("/upload")
public class GovWordController {
@Autowired
private UploadService uploacService;
@PostMapping("/updateImage")
public QueryResult<java.lang.String> updateImage(@RequestParam("image") MultipartFile multfiles,@RequestParam("savePath") String savePath) throws FileNotFoundException {
return uploacService.uploaded(multfiles,savePath);
}
}
Service层接口层(UploadService )
public interface UploadService {
QueryResult<String> uploaded(MultipartFile multipartFile,String saveValue) throws FileNotFoundException;
}
Service层实现层
@Transactional
@Service
public class UploadServiceImpl implements UploadService {
@Override
public QueryResult<String> uploaded(MultipartFile multipartFile,String saveValue) throws FileNotFoundException {
//指定的地址
String fristPath = "/home/jsbg/image";
//指定文件时间
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
double fileSize = multipartFile.getSize();
System.out.println("文件的大小是"+ fileSize);
//获取文件的后缀名
String ext = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
String filePath ="";//上传到服务器的路径
String date = sdf.format(new Date()); //当前日期
//给上传文件命名重新命名,防止重名文件
String uuid = UUID.randomUUID().toString().replace("-", "");
//如果没有指定自己的路径,那么就放到基本路径下
if (StringUtil.isEmpty(saveValue)){
filePath = fristPath+"/"+date; //最终的构造结果为: img/20120512/ssadsd2323232312323.img
}else{
filePath = fristPath+"/"+saveValue+"/"+date; //最终的构造结果为: img/20120512/ssadsd2323232312323.img
}
String newFileName = uuid+ext;//名字
String fileBucketUrl = ""; //上传文件成功后 文件的完整访问地址
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = null;
try {
//lastFilePath = filePath + File.separator + newFileName;
//File.separator相当于 "/"
File file = new File(filePath+"/"+newFileName);
out = new FileOutputStream(file);
out.write(multipartFile.getBytes());
//最终的url地址
fileBucketUrl = filePath;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (fileBucketUrl == null) {
System.out.println("图片上传失败!");
return new QueryResult<>(ResponseEnum.INVALID_PARAM,fileBucketUrl);
}
System.out.println("上传成功!");;
return new QueryResult<>(ResponseEnum.SUCCESS,fileBucketUrl);
}
}
可以使用Postman来测试接口
请求路径
localhost:8081/upload/updateImage?savePath=b
在Body中,选中form-data,要上传的图片(QQ截图20201013152909.png)
要上传的路径
postman上返回的结果
上传成功的图片和地址