DEV Community

badruti94
badruti94

Posted on

Upload file dengan cloudinary di go

#go
func uploadFile(c *gin.Context) (string, error) {
    file, err := c.FormFile("photo")
    if err != nil {
        return "", err
    }
    fileContent, err := file.Open()
    if err != nil {
        return "", err
    }

    fileContent.Close()

    cloud_name := os.Getenv("CLOUDINARY_NAME")
    api_key := os.Getenv("CLOUDINARY_API_KEY")
    api_secret := os.Getenv("CLOUDINARY_API_SECRET")

    cld, _ := cloudinary.NewFromParams(cloud_name, api_key, api_secret)

    var ctx = context.Background()

    randomNumber := strconv.FormatInt(time.Now().UnixNano(), 24)

    resp, err := cld.Upload.Upload(ctx, fileContent, uploader.UploadParams{PublicID: randomNumber})
    if err != nil {
        return "", err
    }

    return resp.SecureURL, nil

}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)