Cloudreve/service/file/upload.go

56 lines
1.5 KiB
Go
Raw Normal View History

2019-11-15 18:12:34 +08:00
package file
2019-11-16 13:37:42 +08:00
import (
2019-11-16 20:31:34 +08:00
"context"
2019-11-17 13:50:14 +08:00
model "github.com/HFO4/cloudreve/models"
2019-11-16 16:11:37 +08:00
"github.com/HFO4/cloudreve/pkg/filesystem"
"github.com/HFO4/cloudreve/pkg/filesystem/local"
"github.com/HFO4/cloudreve/pkg/serializer"
2019-11-16 13:37:42 +08:00
"github.com/gin-gonic/gin"
"mime/multipart"
)
// UploadService 本地策略文件上传服务
type UploadService struct {
Name string `form:"name" binding:"required,lte=255"`
Path string `form:"path" binding:"lte=65536"`
File *multipart.FileHeader `form:"file" binding:"required"`
}
// Upload 处理本地策略小文件上传
2019-11-16 20:31:34 +08:00
func (service *UploadService) Upload(ctx context.Context, c *gin.Context) serializer.Response {
2019-11-16 13:37:42 +08:00
// TODO 检查文件大小是否小于分片最大大小
file, err := service.File.Open()
if err != nil {
return serializer.Err(serializer.CodeIOFailed, "无法打开上传数据", err)
}
fileData := local.FileData{
MIMEType: service.File.Header.Get("Content-Type"),
File: file,
Size: uint64(service.File.Size),
2019-11-16 16:05:10 +08:00
Name: service.Name,
2019-11-16 13:37:42 +08:00
}
user, _ := c.Get("user")
2019-11-17 13:50:14 +08:00
// 创建文件系统
fs, err := filesystem.NewFileSystem(user.(*model.User))
if err != nil {
return serializer.Err(serializer.CodePolicyNotAllowed, err.Error(), err)
2019-11-16 13:37:42 +08:00
}
2019-11-16 16:05:10 +08:00
2019-11-17 13:50:14 +08:00
// 给文件系统分配钩子
fs.BeforeUpload = filesystem.GenericBeforeUpload
// 执行上传
2019-11-16 20:31:34 +08:00
err = fs.Upload(ctx, fileData)
2019-11-16 16:05:10 +08:00
if err != nil {
return serializer.Err(serializer.CodeUploadFailed, err.Error(), err)
}
2019-11-16 13:37:42 +08:00
return serializer.Response{
Code: 0,
Msg: "Pong",
}
}