1.效果 2.配置 2.1 在init中添加图片上传函数 // 图片上传 images_upload_handler: (blobInfo, success, failure) = { // const img = 'data:image/jpeg;base64,' + blobInfo.base64() // success(img) if(blobInfo.blob().size/1024/10242
1.效果



2.配置
2.1 在init中添加图片上传函数
// 图片上传
images_upload_handler: (blobInfo, success, failure) => {
// const img = 'data:image/jpeg;base64,' + blobInfo.base64()
// success(img)
if(blobInfo.blob().size/1024/1024>2){
failure("上传失败,图片大小请控制在 2M 以内")
}else{
let params=new FormData()
params.append('file',blobInfo.blob())
let config={
headers:{
"Content-Type":"multipart/form-data"
}
}
this.axios.post(`/article/upload`,params,config).then(res=>{//使用axios进行图片上传,注意this是否引入成功
success(res.data)
}).catch(()=>{
failure("上传出错,服务器开小差了呢")
})
}
},
如果使用axios进行异步上传,请注意this是否引入成功,有时this会指向tinymce而不是全局的vue,如果发生可以在本组件中单独引入axios
2.2 springboot实现图片上传
@CrossOrigin//跨域设置,如果存在跨域,需再进行设置,后续文章会进行更新
@RestController
@RequestMapping("/article")
public class ArticleController {
@RequestMapping(value = "/upload")
// @RequestParam中的file名应与前端的值保持一致
public String upload(HttpServletResponse response,@RequestParam("file") MultipartFile multipartFile) throws IOException {
System.out.println("访问");
String url=UpLoadFile.uploadPic(multipartFile);
System.out.println("图片的路径是:"+url);
url="http://localhost:8090/image/"+url;
return url;
}
}
2.3 图片上传类UpLoadFile
package com.maque.util;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
public class UpLoadFile {
//判断文件是否存在,存在先进行删除
public void fileHasExist(String filePath,String fileName) {
String path = filePath + fileName;
File file = new File(path);
//判断文件夹是否存在如果不存在,则创建该文件夹
File fileParent = file.getParentFile();
if(!fileParent.exists()){
fileParent.mkdirs();
}
//判断文件是否存在,存在则删除进行新建,不存在则直接新建
if(file.exists()){
file.delete();
System.out.println("file has exist!");
}else{
System.out.println("file has not exist!");
}
}
//上传图片功能
public static String uploadPic(MultipartFile pictureFile) throws IOException {
// 图片上传
// 设置图片名称,不能重复,可以使用uuid
String picName = UUID.randomUUID().toString();
// 获取文件名
String oriName = pictureFile.getOriginalFilename();
// 获取图片后缀
String extName = oriName.substring(oriName.lastIndexOf("."));
// 开始上传保存到指定位置
pictureFile.transferTo(new File(Constant.PICTURE_LOCATION + picName + extName));
//pictureFile.transferTo(new File(ResourceUtils.getURL("classpath:").getPath()+"image/" + picName + extName));
String pName=picName + extName;
return pName;
}
}
Constant.PICTURE_LOCATION是自己定义的文件上传路径的常量
