Improve UploadFile() API.

This commit is contained in:
Yang Luo
2021-08-14 15:58:12 +08:00
parent b7e0a4fe4e
commit 004282f970
5 changed files with 48 additions and 51 deletions

View File

@ -15,10 +15,11 @@
package controllers
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
"github.com/casbin/casdoor/object"
"github.com/casbin/casdoor/original"
@ -214,9 +215,10 @@ func (c *ApiController) GetAccount() {
// UploadFile
// @Title UploadFile
// @Description upload file
// @Param folder query string true "The folder"
// @Param subFolder query string true "The sub folder"
// @Param file formData string true "The file"
// @Param owner query string true "The owner"
// @Param tag query string true "The tag"
// @Param fullFilePath query string true "The full file path"
// @Param file query string true "The file"
// @Success 200 {object} controllers.Response The Response object
// @router /upload-file [post]
func (c *ApiController) UploadFile() {
@ -225,8 +227,23 @@ func (c *ApiController) UploadFile() {
return
}
folder := c.Input().Get("folder")
subFolder := c.Input().Get("subFolder")
//owner := c.Input().Get("owner")
tag := c.Input().Get("tag")
parent := c.Input().Get("parent")
fullFilePath := c.Input().Get("fullFilePath")
file, _, err := c.GetFile("file")
defer file.Close()
if err != nil {
c.ResponseError(err.Error())
return
}
fileBuffer := bytes.NewBuffer(nil)
if _, err = io.Copy(fileBuffer, file); err != nil {
c.ResponseError(err.Error())
return
}
user := object.GetUser(userId)
application := object.GetApplicationByUser(user)
@ -235,38 +252,22 @@ func (c *ApiController) UploadFile() {
c.ResponseError("No storage provider is found")
return
}
file, header, err := c.GetFile("file")
defer file.Close()
fileUrl, err := object.UploadFile(provider, fullFilePath, fileBuffer)
if err != nil {
c.ResponseError(err.Error())
return
}
fileType := header.Header.Get("Content-Type")
fileSuffix := ""
switch fileType {
case "image/png":
fileSuffix = "png"
case "text/html":
fileSuffix = "html"
}
fileUrl, err := object.UploadFile(provider, folder, subFolder, file, fileSuffix)
if err != nil {
c.ResponseError(err.Error())
return
}
switch folder {
switch tag {
case "avatar":
user.Avatar = fileUrl
object.UpdateUser(user.GetId(), user)
case "termsofuse":
appId := fmt.Sprintf("admin/%s", strings.Split(subFolder, "/")[0])
app := object.GetApplication(appId)
case "termsOfUse":
applicationId := fmt.Sprintf("admin/%s", parent)
app := object.GetApplication(applicationId)
app.TermsOfUse = fileUrl
object.UpdateApplication(appId, app)
object.UpdateApplication(applicationId, app)
}
c.ResponseOk(fileUrl)