123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- package upload
- import (
- "fmt"
- "kpt-pasture/config"
- "net/http"
- "os"
- "time"
- "gitee.com/xuyiping_admin/pkg/apierr"
- "gitee.com/xuyiping_admin/pkg/xerr"
- "github.com/gin-gonic/gin"
- )
- func Photos(c *gin.Context) {
- form, err := c.MultipartForm()
- if err != nil {
- apierr.AbortBadRequest(c, http.StatusBadRequest, xerr.Customf("No multipartForm: %s", err.Error()))
- return
- }
- files := form.File["uploads"]
- // 验证文件数量
- if len(files) == 0 {
- apierr.AbortBadRequest(c, http.StatusBadRequest, xerr.Custom("No files selected"))
- return
- }
- workDir := fmt.Sprintf("%s", config.WorkDir)
- pathDir := fmt.Sprintf("/files/photos/%s", time.Now().Format("20060102"))
- saveDir := fmt.Sprintf("%s/%s", workDir, pathDir)
- if _, err = os.Stat(saveDir); os.IsNotExist(err) {
- if err = os.MkdirAll(saveDir, 0755); err != nil {
- apierr.AbortBadRequest(c, http.StatusBadRequest, xerr.Customf("创建目录失败: %s", err.Error()))
- return
- }
- }
- // 处理每个文件
- filePaths := make([]string, len(files))
- timestamp := time.Now().Unix()
- for i, file := range files {
- if file.Header.Get("Content-Type") != "image/jpeg" &&
- file.Header.Get("Content-Type") != "image/png" &&
- file.Header.Get("Content-Type") != "image/gif" {
- apierr.AbortBadRequest(c, http.StatusBadRequest, xerr.Customf("图片格式错误: %s", file.Filename))
- return
- }
- if file.Size > 1024*1024*5 {
- apierr.AbortBadRequest(c, http.StatusBadRequest, xerr.Custom("单个图片文件不能超过5MB"))
- return
- }
- fpath := fmt.Sprintf("%s/%d_%d_%s", saveDir, timestamp, i+1, file.Filename)
- urlPath := fmt.Sprintf("%s/%d_%d_%s", pathDir, timestamp, i+1, file.Filename)
- if err = c.SaveUploadedFile(file, fpath); err != nil {
- apierr.AbortBadRequest(c, http.StatusBadRequest, xerr.Customf("保存文件失败: %s", err.Error()))
- return
- }
- filePaths[i] = urlPath
- }
- c.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "Msg": "ok", "data": filePaths})
- }
- func Files(c *gin.Context) {
- }
- func OssVideo(c *gin.Context) {
- filename := c.Param("name")
- videoPath := fmt.Sprintf("%s/files/video/%s", config.WorkDir, filename)
- // 打开视频文件
- file, err := os.Open(videoPath)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{"error": "Video not found"})
- return
- }
- defer file.Close()
- fileInfo, err := file.Stat()
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not get file info"})
- return
- }
- // 设置响应头
- c.Header("Content-Type", "video/mp4")
- c.Header("Content-Length", fmt.Sprintf("%d", fileInfo.Size()))
- // 流式传输文件内容
- http.ServeContent(c.Writer, c.Request, fileInfo.Name(), fileInfo.ModTime(), file)
- }
|