fix
This commit is contained in:
@@ -3,8 +3,11 @@ package handlers
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"fishfish/database"
|
||||
"fishfish/models"
|
||||
@@ -116,3 +119,46 @@ func GetCategories(c *gin.Context) {
|
||||
|
||||
c.JSON(http.StatusOK, categories)
|
||||
}
|
||||
|
||||
func UploadItemAvatar(c *gin.Context) {
|
||||
itemID := c.Param("id")
|
||||
|
||||
var item models.Item
|
||||
|
||||
if err := database.DB.First(&item, itemID).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Товар не найден"})
|
||||
return
|
||||
}
|
||||
|
||||
file, err := c.FormFile("avatar")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Файл не найден в запросе"})
|
||||
return
|
||||
}
|
||||
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Не удалось открыть файл"})
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
img, err := imaging.Decode(src)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Не удалось обработать фотографию"})
|
||||
return
|
||||
}
|
||||
|
||||
resized := imaging.Resize(img, 1200, 0, imaging.Lanczos)
|
||||
uniqueName := uuid.New().String() + ".jpg"
|
||||
dstPath := filepath.Join("./uploads/items", uniqueName)
|
||||
|
||||
if err := imaging.Save(resized, dstPath, imaging.JPEGQuality(82)); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Не удалось сохранить фотографию"})
|
||||
return
|
||||
}
|
||||
|
||||
item.AvatarURL = "/uploads/items" + uniqueName
|
||||
database.DB.Save(&item)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"avatar_url": item.AvatarURL})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user