本章节的内容比较简单,主要是实现文章附件的上传,已经展示处理。
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
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/98496.html