代码初始化
This commit is contained in:
68
controller/common/upload.go
Normal file
68
controller/common/upload.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
)
|
||||
|
||||
var allowedExts = map[string]bool{
|
||||
".mp4": true, ".avi": true, ".mov": true, ".mkv": true,
|
||||
".flv": true, ".wmv": true, ".webm": true, ".m4v": true,
|
||||
".ts": true, ".mpeg": true, ".mpg": true,
|
||||
}
|
||||
|
||||
// SaveUploadedFiles 保存上传的视频文件,返回本地路径列表
|
||||
func SaveUploadedFiles(r *ghttp.Request) ([]string, error) {
|
||||
ctx := r.Context()
|
||||
tempDir := getTempDir(ctx)
|
||||
os.MkdirAll(tempDir, 0755)
|
||||
|
||||
files := r.GetUploadFiles("files")
|
||||
if len(files) == 0 {
|
||||
if f := r.GetUploadFile("file"); f != nil {
|
||||
files = append(files, f)
|
||||
}
|
||||
}
|
||||
|
||||
var saved []string
|
||||
for _, f := range files {
|
||||
ext := filepath.Ext(f.Filename)
|
||||
if !allowedExts[ext] {
|
||||
continue
|
||||
}
|
||||
savePath := filepath.Join(tempDir, fmt.Sprintf("%d_%s", time.Now().UnixMilli(), f.Filename))
|
||||
src, err := f.Open()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
dst, err := os.Create(savePath)
|
||||
if err != nil {
|
||||
src.Close()
|
||||
continue
|
||||
}
|
||||
io.Copy(dst, src)
|
||||
src.Close()
|
||||
dst.Close()
|
||||
saved = append(saved, savePath)
|
||||
}
|
||||
return saved, nil
|
||||
}
|
||||
|
||||
func getTempDir(ctx context.Context) string {
|
||||
tempDir := g.Cfg().MustGet(ctx, "ffmpeg.temp_dir", "resource/temp").String()
|
||||
if tempDir == "" {
|
||||
tempDir = "resource/temp"
|
||||
}
|
||||
if !filepath.IsAbs(tempDir) {
|
||||
absDir, _ := filepath.Abs(tempDir)
|
||||
tempDir = absDir
|
||||
}
|
||||
return tempDir
|
||||
}
|
||||
Reference in New Issue
Block a user