Revel 使用UEditor、七牛云存储的例子

分享admin2901 次浏览

如果没有七牛账号,点击https://portal.qiniu.com/signup?code=3lftkx0n75iz5注册。

package models

import (
	. "github.com/qiniu/api/conf"
	"github.com/robfig/config"
)

func Init() {
	c, err := config.ReadDefault(revel.BasePath + "/conf/my.conf")
	if err != nil {
		panic(err)
	}

	ACCESS_KEY, _ = c.String("qiniu", "access_key")
	SECRET_KEY, _ = c.String("qiniu", "secret_key")
	QiniuScope, _ = c.String("qiniu", "scope")
	QiniuDomain, _ = c.String("qiniu", "domain")

}
package controllers

import (
	"io"

	qio "github.com/qiniu/api/io"
	"github.com/qiniu/api/rs"
	"github.com/qiniu/api/rsf"
	"github.com/robfig/revel"

	"gorevel/app/models"
)

type Ajax struct {
	*revel.Controller
}

func (c Ajax) UeUploadImage() revel.Result {
	var err error
	var ret qio.PutRet
	var policy = rs.PutPolicy{
		Scope: models.QiniuScope,
	}

	file, header, _ := c.Request.FormFile("upfile")
        defer file.Close()

	err = qio.Put(nil, &ret, policy.Token(nil), header.Filename, file, nil)

	if err != nil {
		revel.ERROR.Println("io.Put failed:", err)
		return c.RenderJson(map[string]string{
			"state": "UNKNOWN",
		})
	} else {
		return c.RenderJson(map[string]string{
			"url":      models.QiniuDomain + ret.Key, 
			"title":    "",
			"original": header.Filename,
			"state":    "SUCCESS", 
		})
	}
}

func (c Ajax) UeGetImages() revel.Result {
	var client rsf.Client
	client = rsf.New(nil)
	entries := listAll(&client, models.QiniuScope, "")

	imageUrls := ""
	for _, entry := range entries {
		imageUrls += models.QiniuDomain + entry.Key + "ue_separate_ue"
	}

	return c.RenderText(imageUrls)
}

func listAll(rs *rsf.Client, bucketName string, prefix string) []rsf.ListItem {

	var entries, files []rsf.ListItem
	var marker = ""
	var err error
	var limit = 0

	for err == nil {
		entries, marker, err = rs.ListPrefix(nil, bucketName,
			prefix, marker, limit)
		for _, item := range entries {
			files = append(files, item)
		}
	}
	if err != io.EOF {
		revel.ERROR.Println("listAll failed:", err)
	}

	return files
}
{{append . "moreScripts" "/public/ue/ueditor.config.js"}}
{{append . "moreScripts" "/public/ue/ueditor.all.js"}}
{{append . "moreScripts" "/public/ue/lang/en/en.js"}}

...

    {{with $field := field "content" .}}
    <div class="form-group">
        <label for="" class="col-sm-2 control-label">Content</label>
        <div class="col-sm-10">
            <textarea type="text" id="{{$field.Name}}" name="{{$field.Name}}"></textarea>
            <span class="text-danger">{{$field.Error}}</span>
        </div>
    </div>
    {{end}}

...

<script type="text/javascript">
    UE.getEditor('content', {
        initialFrameHeight:320  //初始化编辑器高度,默认320

        ,imageUrl: "{{url "Ajax.UeUploadImage"}}"
        ,imagePath: ""
        ,savePath: ["public"]

        //图片在线管理配置区
        ,imageManagerUrl: "{{url "Ajax.UeGetImages"}}"
        ,imageManagerPath: ""

    });
</script>
共0个回复