做富文本图片上传倒腾了半天,该接口前台上传图片保存到后台指定路径,并返回可直接访问图片的链接
@PostMapping("/upload")
public Map<String,Object> fileupload(@RequestParam(value = "file") MultipartFile file){
//判断文件扩展名,如果是png格式则改为1
int end=0;
Map<String,Object> result=new HashMap<>();
System.out.println(file);
//检查文件扩展名
String originName = file.getOriginalFilename();
if(!originName.endsWith(".jpg")){
end=1;
if(!originName.endsWith(".png")){
result.put("errno",1);
result.put("msg","文件类型不对");
System.out.println("类型");
return result;
}
}
//图片保存的位置
String realPath="/E:/JavaGo/SWX/src/main/resources//static//swxadm/images";
File folder=new File(realPath);
if(!folder.exists()){
folder.mkdirs();
}
//生成文件名
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = simpleDateFormat.format(date);
String imgsrc="/E:/JavaGo/SWX/src/main/resources//static//swxadm/images/"+fileName;
//创建该文件
File file1=new File(imgsrc);
if(!file1.exists()){
String newName;
//判断文件后缀
if(end==0){
newName=fileName+".jpg";
}else {
newName=fileName+".png";
}
try {
file.transferTo(new File(folder,newName));
Map<String,Object> data=new HashMap<>();
//拼接访问地址返回,这里端口和路径改成你自己的
data.put("url","http://localhost:8085/swxadm/images/"+newName);
data.put("alt",newName);
data.put("href","http://localhost:8085/swxadm/images/"+newName);
result.put("errno",0);
result.put("data",data);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("已完成上传");
}
return result;
}
测试:
保存到后台的图片:
访问返回的链接:
版权声明:本文为qq_20249821原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。