golang beego框架学习(七)

AndyYang| 阅读:1982 发表时间:2017-04-25 21:50:14 golang
摘要:本章节的内容比较简单,主要是实现文章附件的上传,已经展示处理。
本章节的内容比较简单,主要是实现文章附件的上传,已经展示处理。

1、修改controller下topic.go的post处理方法,添加源码:
_, fh, err := this.GetFile("attachment")
if err != nil {
    beego.Error(err)
}

var attachment string
if fh != nil {
    // 保存附件
    attachment = fh.Filename
    beego.Info(attachment)
    err = this.SaveToFile("attachment", path.Join("attachment", attachment))
    if err != nil {
        beego.Error(err)
    }
}

if len(tid) == 0 {
    err = models.AddTopic(title, category, lable, content, attachment)
} else {
    err = models.ModifyTopic(tid, title, category, lable, content, attachment)
}
2、models下models.go文件小调,添加attachment的入库处理,以及附件的删除处理:
if len(oldAttach) > 0 && oldAttach != topic.Attachment {
    os.Remove(path.Join("attachment", oldAttach))
}
3、附件的展示:
方法一:
beego.SetStaticPath("/attachment", "attachment")
方法二:
beego.Router("/attachment/:all", &controllers.AttachController{})
需新增controllers/attach.go,源码:
package controllers

import (
    "github.com/astaxie/beego"
    "io"
    "net/url"
    "os"
)

type AttachController struct {
    beego.Controller
}

func (this *AttachController) Get() {
    filePath, err := url.QueryUnescape(this.Ctx.Request.RequestURI[1:])
    if err != nil {
        this.Ctx.WriteString(err.Error())
        return
    }

    f, err := os.Open(filePath)
    if err != nil {
        this.Ctx.WriteString(err.Error())
        return
    }
    defer f.Close()

    _, err = io.Copy(this.Ctx.ResponseWriter, f)
    if err != nil {
        this.Ctx.WriteString(err.Error())
        return
    }
}

github:https://github.com/yangsir/beego_study

本文为AndyYang原创,转载请注明出处!
如果您觉得好,可以打赏作者:
如果您觉得累了,是否想看点美女养养眼:猛戳>>朋友帮
如果您觉得皮了,是否想来点神吐槽:猛戳>>iPhone查询中

已有0条评论

昵称:
邮箱:

  • 最新评论

iPhone查询中 - bbs.ipcxz.com 朋友帮 - www.pengyb.cn iPhone查询中 - bbs.ipcxz.com
反馈
微信订阅号