Skip to content

Commit

Permalink
附件上传管理优化
Browse files Browse the repository at this point in the history
  • Loading branch information
TruthHun88 committed Dec 30, 2020
1 parent b4f9225 commit ebb8a8a
Show file tree
Hide file tree
Showing 7 changed files with 63 additions and 119 deletions.
5 changes: 4 additions & 1 deletion change.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,14 @@

## v2.10 升级日志
- [x] 支持音频和视频上传
- [ ] 如果开启了OSS云存储,则将音视频上传上去的同时将音视频设置为私有
- [x] 支持音频和视频播放管理
- [x] 管理后台,恢复和优化附件管理功能
- [ ] 如果管理员或者用户是书籍项目所有人,则音视频链接支持直链播放,否则对音视频链接进行一定的防盗链处理
- [ ] 内容阅读页面音频视频播放功能
- [ ] ajax加载内容时,音视频不显示的问题
- [ ] 音频和视频播放倍速控制
- [ ] 音视频名称显示
- [ ] 视频画中画播放
- [x] 增加和升级API,使小程序和APP支持音频和视频播放,以及图片放大预览
- [x] 优化`html2json`仓库,解析`HTML`内容,使小程序支持音频和视频播放功能,以及图片放大预览功能
- [ ] 检测和隐藏相关功能
Expand Down
2 changes: 1 addition & 1 deletion commands/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ func ResolveCommand(args []string) {
os.MkdirAll(uploads, 0666)

beego.BConfig.WebConfig.StaticDir["/static"] = filepath.Join("static")
beego.BConfig.WebConfig.StaticDir["/uploads"] = uploads
// beego.BConfig.WebConfig.StaticDir["/uploads"] = uploads
beego.BConfig.WebConfig.ViewsPath = filepath.Join("views")

fonts := filepath.Join("static", "fonts")
Expand Down
3 changes: 1 addition & 2 deletions controllers/BookController.go
Original file line number Diff line number Diff line change
Expand Up @@ -690,9 +690,8 @@ func (this *BookController) Delete() {
this.JsonResult(0, "ok")
}

//发布书籍.
// 发布书籍.
func (this *BookController) Release() {

identify := this.GetString("identify")
bookId := 0
if this.Member.IsAdministrator() {
Expand Down
95 changes: 28 additions & 67 deletions controllers/DocumentController.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,15 @@ func (this *DocumentController) Read() {
attach, err := models.NewAttachment().FindListByDocumentId(doc.DocumentId)
if err == nil {
doc.AttachList = attach
if len(attach) > 0 {
content := bytes.NewBufferString("<div class=\"attach-list\"><strong>附件</strong><ul>")
for _, item := range attach {
li := fmt.Sprintf("<li><a href=\"%s\" target=\"_blank\" title=\"%s\">%s</a></li>", item.HttpPath, item.FileName, item.FileName)
content.WriteString(li)
}
content.WriteString("</ul></div>")
doc.Release += content.String()
}
}

//文档阅读人次+1
Expand Down Expand Up @@ -632,7 +641,6 @@ func (this *DocumentController) Upload() {
identify := this.GetString("identify")
docId, _ := this.GetInt("doc_id")
fileType := this.GetString("type")
isAttach := true

if identify == "" {
this.JsonResult(6001, "参数错误")
Expand Down Expand Up @@ -717,105 +725,58 @@ func (this *DocumentController) Upload() {

fileName := strconv.FormatInt(time.Now().UnixNano(), 16)

filePath := filepath.Join("uploads/projects", bookIdentify, time.Now().Format("200601"), fileName+ext)

path := filepath.Dir(filePath)

os.MkdirAll(path, os.ModePerm)

err = this.SaveToFile(name, filePath)
prefix := "uploads"
savePath := filepath.Join("projects", bookIdentify, time.Now().Format("200601"), fileName+ext)
if utils.StoreType != utils.StoreOss {
savePath = filepath.Join(prefix, savePath)
}
savePath = strings.ReplaceAll(savePath, "\\", "/")
os.MkdirAll(filepath.Dir(savePath), os.ModePerm)

err = this.SaveToFile(name, savePath)
if err != nil {
beego.Error("SaveToFile => ", err)
this.JsonResult(6005, "保存文件失败")
}

attachment := models.NewAttachment()
attachment.BookId = bookId
attachment.FileName = moreFile.Filename
attachment.CreateAt = this.Member.MemberId
attachment.FileExt = ext
attachment.FilePath = filePath
attachment.FilePath = "/" + savePath
attachment.HttpPath = attachment.FilePath
attachment.DocumentId = docId

// 非附件
if name != "editormd-file-file" {
attachment.DocumentId = 0
}

if fileInfo, err := os.Stat(filePath); err == nil {
if fileInfo, err := os.Stat(savePath); err == nil {
attachment.FileSize = float64(fileInfo.Size())
}

if strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".jpeg") || strings.EqualFold(ext, ".png") || strings.EqualFold(ext, ".gif") {

attachment.HttpPath = "/" + strings.Replace(filePath, "\\", "/", -1)
if strings.HasPrefix(attachment.HttpPath, "//") {
attachment.HttpPath = string(attachment.HttpPath[1:])
}
isAttach = false
}

err = attachment.Insert()

if err != nil {
os.Remove(filePath)
// 数据入库
if err = attachment.Insert(); err != nil {
os.Remove(savePath)
beego.Error("Attachment Insert => ", err)
this.JsonResult(6006, "文件保存失败")
}
if attachment.HttpPath == "" {
attachment.HttpPath = beego.URLFor("DocumentController.DownloadAttachment", ":key", identify, ":attach_id", attachment.AttachmentId)

if err := attachment.Update(); err != nil {
beego.Error("SaveToFile => ", err)
this.JsonResult(6005, "保存文件失败")
}
}

//文件和图片分开放在书籍文件夹内
var osspath = ""
if strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".jpeg") || strings.EqualFold(ext, ".png") || strings.EqualFold(ext, ".gif") {
osspath = fmt.Sprintf("projects/%v/%v", identify, fileName+filepath.Ext(attachment.HttpPath))
} else {
osspath = strings.Replace(filepath.Join("projects", identify, "files", fileName+ext), "\\", "/", -1)
}

switch utils.StoreType {
case utils.StoreOss:
if err := store.ModelStoreOss.MoveToOss("."+attachment.HttpPath, osspath, true, false); err != nil {
if utils.StoreType == utils.StoreOss {
if err := store.ModelStoreOss.MoveToOss(savePath, savePath, true, false); err != nil {
beego.Error(err.Error())
}
//attachment.HttpPath = this.OssDomain + "/" + osspath
attachment.HttpPath = "/" + osspath
case utils.StoreLocal:
osspath = "uploads/" + osspath
//图片是正确的,先不修改
if strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".jpeg") || strings.EqualFold(ext, ".png") || strings.EqualFold(ext, ".gif") {
if err := store.ModelStoreLocal.MoveToStore("."+attachment.HttpPath, osspath); err != nil {
beego.Error(err.Error())
}
attachment.HttpPath = "/" + osspath
attachment.FilePath = attachment.HttpPath
} else {
if err := store.ModelStoreLocal.MoveToStore(filePath, osspath); err != nil {
beego.Error(err.Error())
}
attachment.FilePath = osspath
}
if err := attachment.Update(); err != nil {
beego.Error("SaveToFile => ", err)
this.JsonResult(6005, "保存文件失败")
}
}

attachment.HttpPath = "/" + strings.TrimLeft(attachment.FilePath, "./")

result := map[string]interface{}{
"errcode": 0,
"success": 1,
"message": "ok",
"url": attachment.HttpPath,
"alt": attachment.FileName,
"is_attach": isAttach,
"is_attach": attachment.DocumentId > 0,
"attach": attachment,
}
this.Ctx.Output.JSON(result, true, false)
Expand Down Expand Up @@ -973,7 +934,7 @@ func (this *DocumentController) Delete() {
this.JsonResult(0, "ok")
}

//获取或更新文档内容.
// 获取或更新文档内容.
func (this *DocumentController) Content() {
identify := this.Ctx.Input.Param(":key")
docId, err := this.GetInt("doc_id")
Expand Down
55 changes: 18 additions & 37 deletions controllers/StaticController.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
package controllers

import (
"io/ioutil"
"fmt"
"net/http"
"path/filepath"
"strings"
"time"

"github.com/TruthHun/BookStack/models"

"github.com/TruthHun/BookStack/models/store"
"github.com/TruthHun/BookStack/utils"
"github.com/astaxie/beego"
)

type StaticController struct {
beego.Controller
OssDomain string
}

func (this *StaticController) Prepare() {
this.OssDomain = strings.TrimRight(beego.AppConfig.String("oss::Domain"), "/ ")
}

func (this *StaticController) APP() {
Expand All @@ -26,6 +29,16 @@ func (this *StaticController) APP() {
this.Abort("404")
}

// Uploads 查询上传的静态资源。
// 如果是音频和视频文件,需要根据后台设置而判断是否加密处理
// 如果使用了OSS存储,则需要将文件处理好
func (this *StaticController) Uploads() {
file := strings.TrimLeft(this.GetString(":splat"), "./")
path := strings.ReplaceAll(filepath.Join("uploads", file), "\\", "/")
fmt.Println("===========", path)
http.ServeFile(this.Ctx.ResponseWriter, this.Ctx.Request, path)
}

//静态文件,这个加在路由的最后
func (this *StaticController) StaticFile() {
file := this.GetString(":splat")
Expand All @@ -40,41 +53,9 @@ func (this *StaticController) StaticFile() {

// 书籍静态文件
func (this *StaticController) ProjectsFile() {
prefix := "projects/"
object := prefix + strings.TrimLeft(this.GetString(":splat"), "./")

//这里的时间只是起到缓存的作用
t, _ := time.Parse("2006-01-02 15:04:05", "2006-01-02 15:04:05")
date := t.Format(http.TimeFormat)
since := this.Ctx.Request.Header.Get("If-Modified-Since")
if since == date {
this.Ctx.ResponseWriter.WriteHeader(http.StatusNotModified)
return
}

object := filepath.Join("projects/", strings.TrimLeft(this.GetString(":splat"), "./"))
if utils.StoreType == utils.StoreOss { //oss
staticDomain := strings.Trim(beego.AppConfig.DefaultString("static_domain", ""), "/")
if staticDomain == "" {
reader, err := store.NewOss().GetFileReader(object)
if err != nil {
beego.Error(err.Error())
this.Abort("404")
}
defer reader.Close()

b, err := ioutil.ReadAll(reader)
if err != nil {
beego.Error(err.Error())
this.Abort("404")
}
this.Ctx.ResponseWriter.Header().Set("Last-Modified", date)
if strings.HasSuffix(object, ".svg") {
this.Ctx.ResponseWriter.Header().Set("Content-Type", "image/svg+xml")
}
this.Ctx.ResponseWriter.Write(b)
return
}
this.Redirect(staticDomain+"/"+object, 302)
this.Redirect(this.OssDomain+"/"+object, 302)
} else { //local
this.Abort("404")
}
Expand Down
21 changes: 10 additions & 11 deletions models/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (

"github.com/TruthHun/gotil/mdtil"

"bytes"
"fmt"

"io/ioutil"
Expand Down Expand Up @@ -213,16 +212,16 @@ func (m *Document) ReleaseContent(bookId int, baseUrl string) {
}

item.Release = ds.Content
attachList, err := NewAttachment().FindListByDocumentId(item.DocumentId)
if err == nil && len(attachList) > 0 {
content := bytes.NewBufferString("<div class=\"attach-list\"><strong>附件</strong><ul>")
for _, attach := range attachList {
li := fmt.Sprintf("<li><a href=\"%s\" target=\"_blank\" title=\"%s\">%s</a></li>", attach.HttpPath, attach.FileName, attach.FileName)
content.WriteString(li)
}
content.WriteString("</ul></div>")
item.Release += content.String()
}
// attachList, err := NewAttachment().FindListByDocumentId(item.DocumentId)
// if err == nil && len(attachList) > 0 {
// content := bytes.NewBufferString("<div class=\"attach-list\"><strong>附件</strong><ul>")
// for _, attach := range attachList {
// li := fmt.Sprintf("<li><a href=\"%s\" target=\"_blank\" title=\"%s\">%s</a></li>", attach.HttpPath, attach.FileName, attach.FileName)
// content.WriteString(li)
// }
// content.WriteString("</ul></div>")
// item.Release += content.String()
// }

// 采集图片与稳定内容连接替换
if gq, err := goquery.NewDocumentFromReader(strings.NewReader(item.Release)); err == nil {
Expand Down
1 change: 1 addition & 0 deletions routers/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,5 +161,6 @@ func webRouter() {
beego.Router("/local-render", &controllers.LocalhostController{}, "get,post:RenderMarkdown")
beego.Router("/local-render-cover", &controllers.LocalhostController{}, "get:RenderCover")
beego.Router("/projects/*", &controllers.StaticController{}, "get:ProjectsFile")
beego.Router("/uploads/*", &controllers.StaticController{}, "get:Uploads")
beego.Router("/*", &controllers.StaticController{}, "get:StaticFile")
}

0 comments on commit ebb8a8a

Please sign in to comment.