amazon-web-servicesgoaws-lambdaserverless

image failed to show when Upload from Lambda


if run my code from run on localhost then upload to AWS-lambda then if i use the link on browser it will show the image but if i deploy to lambda then upload it, it will not show the image..

i have this code that upload

func UploadFile(uploader *manager.Uploader, key string, file multipart.File, fileHeader *multipart.FileHeader) (string, error) {

    if file == nil {
        return "", errors.New("file is nil")
    }

    contentType := fileHeader.Header.Get("Content-Type")
    if contentType == "" {
        contentType = "application/octet-stream" // Default to binary if content type is not provided
    }

    fileStat, err := fileHeader.Open()
    if err != nil {
        return "", fmt.Errorf("failed to open file for debugging: %w", err)
    }
    defer fileStat.Close()

    if _, err := file.Seek(0, 0); err != nil {
        return "", errors.New("failed to reset file cursor: " + err.Error())
    }

    result, err := uploader.Upload(context.TODO(), &s3.PutObjectInput{
        Bucket:      aws.String("unleap-bucket"),
        Key:         aws.String("uneleap/" + key),
        Body:        file,
        ContentType: aws.String(contentType),
        ACL:         types.ObjectCannedACLPublicRead,
    })

    if err != nil {
        return "", err
    }
    // Ensure the result is not nil and return the location of the uploaded file
    if result == nil || result.Location == "" {
        return "", errors.New("failed to get the uploaded file location")
    }
    return result.Location, err
}

this is kind of surprise to me,

if i upload from localhost link will show but if i upload from lambda it will not show

here is my serverless file

service: uneleap-api-client

frameworkVersion: ">=4.1.19"


provider:
  name: aws
  region: eu-north-1
  runtime: go1.x
  stage: ${opt:stage}
  iam:
    role:
      statements:
        - Effect: "Allow"
          Action:
            - "s3:PutObject"
            - "s3:GetObject"
            - "s3:PutObjectAcl"
          Resource: "arn:aws:s3:::u-bucket/*"

custom:
  hooks:
    'package:initialize': ./scripts/generate_swagger.sh

package:
  patterns:
    - '!*/**'
    - bin/main

functions:
  api:
    handler: bin/main
    events:
      - http:
          path: /{proxy+}
          method: ANY
          cors: true

i added this after a long search but yet no solution

iam:
        role:
          statements:
            - Effect: "Allow"
              Action:
                - "s3:PutObject"
                - "s3:GetObject"
                - "s3:PutObjectAcl"
              Resource: "arn:aws:s3:::u-bucket/*"

Solution

  • Add multipart/form-data to your binary media type..

    so go to Api Gateway then click the Api you are using, then click Api settings at the left hand conner then add it

    Binary media type