vue+axios+TinyMCE图片上传功能
前端
最近在做一个前后端分离的实践,实践当中需要完成文本的编辑,以及图片的上传,在图片上传的地方踩了很多坑最后也没有实现。最后在浏览众多方法后自己试着写了一下,成功!(PS:本人在校大学生,小白一枚,只想留下自己踩的坑)
编辑器
前端编辑器使用的是Tinymce 因为英语很渣,看见英文文档就算有谷歌翻译也不想看,怎么使用的话还请百度,在这人就不多叙述。
编辑器效果如图:
Tinymce图片上传
因为要上传图片到后端所以使用
images_upload_handler
处理图片(即异步上传到服务端)
images_upload_handler包含3个参数blobInfo, success,failure,blobInfo为图片信息,success为上传成功的回调(我的理解是返回图片的url),failure失败的回调。
以下是我的代码(通过axios发送请求)
images_upload_handler: (blobInfo, success,failure) => {
let formdata = new FormData()
formdata.append("file",blobInfo.blob())
this.axios.post('http://127.0.0.1:8089/imgurl',formdata)
.then((res) => {
if (res.data.code == 200) {
success(res.data.msg)
} else {
failure('上传失败!')
}
})
// window.console.log(blobInfo)
// const img = 'data:image/jpeg;base64,' + blobInfo.base64()
// window.console.log(failure,123)
// success(img)
//此处为图片上传处理函数,这个直接用了base64的图片形式上传图片,
}
利用formdata传输数据。
前端完结。详细参考https://www.jianshu.com/p/9c708a47d8a5
后端
后端我这里用的是ssm框架,项目用的是maven,工具IDEA。
配置(important!!!!)
因为要上传文件所以必须添加一下配置不然报错。
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="UTF-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
<!-- 指定上传文件的临时路径 -->
<!-- <property name="uploadTempDir" value="uploadTempDirectory" /> -->
</bean>
后端代码
@RequestMapping("/imgurl")
@CrossOrigin//解决跨域问题
public void test (HttpServletResponse response,@RequestParam("file") MultipartFile file) throws IOException{
if (file.isEmpty()) {
System.out.println("文件为空");
}
String fileName = file.getOriginalFilename();
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 文件上传路径
String filePath = "D:/IDEA_WORK/shijian/web/";
// 解决中文问题,liunx 下中文路径,图片显示问题
//fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
String pre = "http://127.0.0.1:8089/"+fileName;
PrintWriter out = response.getWriter();
this.getJson().setCode("200");
this.getJson().setMsg(pre);
this.getJson().setData(null);
out.println(toJson.gson.toJson(this.getJson()));
out.flush();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Json类
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class json {
private String code;
private String msg;
private Object data;
}
序列化利用的是GSON,序列化为JSON进行传输(我也只知道这么多,想知道更多望百度)