aditya.siregar 67f1dbc850 init project
2024-05-28 14:14:55 +07:00

93 lines
2.4 KiB
Go

package oss
import (
"fmt"
"furtuna-be/internal/entity"
"furtuna-be/internal/handlers/response"
"furtuna-be/internal/services"
"mime/multipart"
"net/http"
"github.com/gin-gonic/gin"
)
const _oneMB = 1 << 20 // 1MB
const _maxUploadSizeMB = 2 * _oneMB
const _folderName = "/file"
type OssHandler struct {
ossService services.OSSService
}
func (h *OssHandler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
route := group.Group("/file")
route.POST("/upload", h.UploadFile, jwt)
}
func NewOssHandler(ossService services.OSSService) *OssHandler {
return &OssHandler{
ossService: ossService,
}
}
// UploadFile handles the uploading of a file to OSS.
// @Summary Upload a file to OSS
// @Description Upload a file to Alibaba Cloud OSS with the provided details.
// @Accept mpfd
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param file formData file true "File to upload (max size: 2MB)"
// @Success 200 {object} response.BaseResponse{data=entity.UploadFileResponse} "File uploaded successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Tags File Upload API
// @Router /api/v1/file/upload [post]
func (h *OssHandler) UploadFile(c *gin.Context) {
// Get the oss file from the request form
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, response.BaseResponse{
ErrorMessage: "Failed to retrieve the file",
})
return
}
// Check if the uploaded file is an image (photo)
//if !isPDFFile(file) {
// c.JSON(http.StatusBadRequest, response.BaseResponse{
// ErrorMessage: "Only image files are allowed",
// })
// return
//}
// Check if the file size is not greater than the maximum allowed size
if file.Size > _maxUploadSizeMB {
c.JSON(http.StatusBadRequest, response.BaseResponse{
ErrorMessage: fmt.Sprintf("The file is too big. The maximum size is %d", _maxUploadSizeMB/_oneMB),
})
return
}
// Call the service to oss the file to Alibaba Cloud OSS
ret, err := h.ossService.UploadFile(c, &entity.UploadFileRequest{
FileHeader: file,
FolderName: _folderName,
})
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Data: ret,
Success: true,
})
}
func isPDFFile(file *multipart.FileHeader) bool {
contentType := file.Header.Get("Content-Type")
return contentType == "application/pdf"
}