后端
注意:文档要求返回Json格式的数据,如:
{"errno":0,"data":["/static/upload/202009/16234.png"]}
func ApiUpload(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(1 << 20 * 20)
fin, h, err := r.FormFile("upload")
if err != nil {
w.Write([]byte("上传失败:" + err.Error()))
}
defer fin.Close()
filename := h.Filename
dir := time.Now().Format("200601/02")
os.Mkdir("./static/upload/"+dir[:6], 0666)
name := "static/upload/" + dir + filename
dst, _ := os.Create(name)
defer dst.Close()
io.Copy(dst, fin)
data := make([]string, 0, 0)
data = append(data, "/"+name)
mod := WangEditorImg{
Errno: 0,
Data: data,
}
// buf, _ := json.Marshal(mod)
// io.WriteString(w, string(buf))
w.Write(mod.WEditorJSON())
}
//wangEditor指定返回json格式
type WangEditorImg struct {
Errno int `json:"errno"`
Data []string `json:"data"`
}
//将wangEditor变成json字符串
func (weditor *WangEditorImg) WEditorJSON() []byte {
buf, _ := json.Marshal(weditor)
return buf
}
JS
var E=window.wangEditor
var editor=new E("#ctn")
//开启debug模式
editor.customConfig.debug = true;
// 关闭粘贴内容中的样式
editor.customConfig.pasteFilterStyle = false
// 忽略粘贴内容中的图片
editor.customConfig.pasteIgnoreImg = true
editor.customConfig.uploadFileName = 'upload'; //设置文件上传的参数名称
editor.customConfig.uploadImgServer = '/api/upload'; //设置上传文件的服务器路径
editor.customConfig.uploadImgMaxSize = 10 * 1024 * 1024; // 将图片大小限制为 3M
editor.customConfig.uploadImgMaxLength = 5;
// editor.customConfig.uploadImgHooks = {
// success: function (xhr, editor, result) {
// // 图片上传并返回结果,图片插入成功之后触发
// // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
// if(xhr.readyState==4 && xhr.status==200){
// // alert("上传图片成功")
// }
// },
// }
editor.create()