1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- 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, "message": "ok", "data": filePaths})
- }
- func Files(c *gin.Context) {
- }
|