golang+wangEditor实现图片上传

本文档介绍如何利用Golang后端配合wangEditor富文本编辑器,实现图片上传的功能。通过Golang处理上传请求,进行文件保存,并返回上传成功的JSON数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

后端

注意:文档要求返回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()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值