78 lines
1.7 KiB
Go
78 lines
1.7 KiB
Go
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
|
|
}
|
|
|
|
// SaveUploadedFilesFromCtx 从请求上下文中获取上传文件并保存
|
|
func SaveUploadedFilesFromCtx(ctx context.Context) ([]string, error) {
|
|
r := g.RequestFromCtx(ctx)
|
|
if r == nil {
|
|
return nil, fmt.Errorf("无法获取请求上下文")
|
|
}
|
|
return SaveUploadedFiles(r)
|
|
}
|
|
|
|
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
|
|
}
|