Upload/Download file CSV/Excel using Amazon Lambda with Go example code

Write example code: AWS Lambda with Go upload file

Here’s an example of an AWS Lambda function written in Go that can handle a file upload:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "io"
    "os"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {

    // Get the file from the request body
    file, header, err := request.GetFile("file")
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to get file from request body",
            StatusCode: 400,
        }, nil
    }
    defer file.Close()

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 PutObjectInput with the file details
    input := &s3.PutObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(header.Filename),
        Body:   file,
    }

    // Upload the file to S3
    _, err = svc.PutObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to upload file to S3",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("File %s uploaded to S3", header.Filename),
        StatusCode: 200,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the file from the request body by calling request.GetFile(“file”), which returns the file, its header, and any error that may have occurred. If there is an error, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the PutObject method to upload the file to S3.
It then creates a response in the form of events.APIGatewayProxyResponse which contains a message about the uploaded file.
You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.

Write example code: AWS Lambda with Go download file

Here’s an example of an AWS Lambda function written in Go that can handle a file download from an S3 bucket:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "io"
    "os"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file name from the request query parameters
    fileName := request.QueryStringParameters["fileName"]
    if fileName == "" {
        return events.APIGatewayProxyResponse{
            Body:       "File name not provided in query parameters",
            StatusCode: 400,
        }, nil
    }

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 GetObjectInput with the file details
    input := &s3.GetObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
    }

    // Download the file from S3
    result, err := svc.GetObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to download file from S3",
            StatusCode: 500,
        }, nil
    }
    defer result.Body.Close()

    // Create a new file with the same name as the file in S3
    out, err := os.Create(fileName)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to create a new file",
            StatusCode: 500,
        }, nil
    }
    defer out.Close()

    // Copy the downloaded file to the new file
    _, err = io.Copy(out, result.Body)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to copy the downloaded file to the new file",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("File %s downloaded from S3", fileName),
        StatusCode: 200,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the file name from the request’s query parameters by calling request.QueryStringParameters[“fileName”], which returns the file name. If the file name is not provided, the function returns a Bad Request error message.

Write example code: AWS Lambda with Go upload CSV file

Here’s an example of an AWS Lambda function written in Go that can handle a CSV file upload to an S3 bucket:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "mime/multipart"
    "io"
    "os"
    "strings"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file from the request body
    file, header, err := request.MultiValueHeaders["Content-File"][0], request.MultiValueHeaders["Content-Type"][0], request.MultiValueHeaders["Content-Disposition"][0]
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "File not found in request body",
            StatusCode: 400,
        }, nil
    }
    defer file.Close()

    // Get the file name from the request headers
    fileName := strings.Split(header, ";")[1]
    fileName = strings.TrimPrefix(fileName, " filename=")

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 PutObjectInput with the file details
    input := &s3.PutObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
        Body:   file,
    }

    // Upload the file to S3
    _, err = svc.PutObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to upload file to S3",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("File %s uploaded to S3", fileName),
        StatusCode: 200,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the file from the request’s body by calling request.MultiValueHeaders[“Content-File”][0] which returns the file. If the file is not provided, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the PutObject method to upload the file to the specified S3 bucket. The function also extracts the file name from the request headers, and the bucket name is hardcoded in the code.

Write example code: AWS Lambda with Go download CSV file

Here’s an example of an AWS Lambda function written in Go that can handle a CSV file download from an S3 bucket:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "net/http"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file name from the request query parameters
    fileName := request.QueryStringParameters["fileName"]
    if fileName == "" {
        return events.APIGatewayProxyResponse{
            Body:       "File name not provided in query parameters",
            StatusCode: 400,
        }, nil
    }

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 GetObjectInput with the file details
    input := &s3.GetObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
    }

    // Download the file from S3
    result, err := svc.GetObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to download file from S3",
            StatusCode: 500,
        }, nil
    }

    // Set the response headers
    headers := make(map[string]string)
    headers["Content-Type"] = "text/csv"
    headers["Content-Disposition"] = "attachment; filename=" + fileName

    return events.APIGatewayProxyResponse{
        Body:       result.Body.(io.ReadCloser),
        StatusCode: http.StatusOK,
        Headers: headers,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the file name from the request’s query parameters by calling request.QueryStringParameters[“fileName”]. If the file name is not provided, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the GetObject method to download the file from the specified S3 bucket. The function also sets the response headers to indicate that the response is a csv file and it is an attachment. The bucket name is hardcoded in the code.

Example code: AWS Lambda with Go upload Excel file

Here’s an example of an AWS Lambda function written in Go that can handle an Excel file upload to an S3 bucket:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "net/http"
    "os"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file name and file content from the request body
    fileName := request.Headers["fileName"]
    fileContent := request.Body
    if fileName == "" || fileContent == "" {
        return events.APIGatewayProxyResponse{
            Body:       "File name or content not provided in request body",
            StatusCode: 400,
        }, nil
    }

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 PutObjectInput with the file details
    input := &s3.PutObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
        Body:   strings.NewReader(fileContent),
    }

    // Upload the file to S3
    _, err := svc.PutObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to upload file to S3",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       "File uploaded successfully",
        StatusCode: http.StatusOK,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the file name and file content from the request body by calling request.Headers[“fileName”] and request.Body respectively. If the file name or content is not provided, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the PutObject method to upload the file to the specified S3 bucket with the provided file name. The function also sets the response headers to indicate that the response is a excel file and it is an attachment. The bucket name is hardcoded in the code.

Example code: AWS Lambda with Go download Excel file

Here’s an example of an AWS Lambda function written in Go that can handle an Excel file download from an S3 bucket:

package main

import (
    "context"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "net/http"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file name from the query string
    fileName := request.QueryStringParameters["fileName"]
    if fileName == "" {
        return events.APIGatewayProxyResponse{
            Body:       "File name not provided in query string",
            StatusCode: 400,
        }, nil
    }

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 GetObjectInput with the file details
    input := &s3.GetObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
    }

    // Download the file from S3
    result, err := svc.GetObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to download file from S3",
            StatusCode: 500,
        }, nil
    }

    // Get the file content
    fileContent, err := ioutil.ReadAll(result.Body)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to read file content",
            StatusCode: 500,
        }, nil
    }

    // Set the response headers to indicate that the response is a excel file and it is an attachment
    headers := make(map[string]string)
    headers["Content-Type"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    headers["Content-Disposition"] = "attachment; filename="+fileName

    return events.APIGatewayProxyResponse{
        Body:       string(fileContent),
        StatusCode: http.StatusOK,
        Headers: headers,
    }, nil
}

func main() {
    lambda.Start(HandleRequest)
}

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function retrieves the file name from the query string by calling request.QueryStringParameters[“fileName”]. If the file name is not provided, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the GetObject method to download the file from the specified S3 bucket with the provided file name. The function also sets the response headers to indicate that the response is a excel

Angular 9 Nodejs/Express MySQL Multer Sequelize – Upload Files/Download Files

Angular 9 Nodejs/Express MySQL Multer Sequelize – Upload Files/Download Files

https://ozenero.com/frontend/angular/angular-6/angular-6-httpclient-upload-files-download-files-to-mysql-with-node-js-express-restapis-using-multer-sequelize-orm

In the tutorial, we show how to upload files, download files from Angular 9 Client to MySQL with Node.js RestAPIs server using Multer middleware and Sequelize ORM.

Related posts:
Node.js/Express RestAPIs server – Angular 9 Upload/Download Files – Multer + Bootstrap
Angular 9 HttpClient Crud + Node.js Express Sequelize + MySQL – Get/Post/Put/Delete RestAPIs

Continue reading “Angular 9 Nodejs/Express MySQL Multer Sequelize – Upload Files/Download Files”

Angular 10 Nodejs/Express MySQL Multer Sequelize – Upload Files/Download Files

Angular 10 Nodejs/Express MySQL Multer Sequelize – Upload Files/Download Files

https://ozenero.com/frontend/angular/angular-6/angular-6-httpclient-upload-files-download-files-to-mysql-with-node-js-express-restapis-using-multer-sequelize-orm

In the tutorial, we show how to upload files, download files from Angular 10 Client to MySQL with Node.js RestAPIs server using Multer middleware and Sequelize ORM.

Related posts:
Node.js/Express RestAPIs server – Angular 10 Upload/Download Files – Multer + Bootstrap
Angular 10 HttpClient Crud + Node.js Express Sequelize + MySQL – Get/Post/Put/Delete RestAPIs

Continue reading “Angular 10 Nodejs/Express MySQL Multer Sequelize – Upload Files/Download Files”

Angular 11 Nodejs/Express MySQL Multer Sequelize – Upload Files/Download Files

Angular 11 Nodejs/Express MySQL Multer Sequelize – Upload Files/Download Files

https://ozenero.com/frontend/angular/angular-6/angular-6-httpclient-upload-files-download-files-to-mysql-with-node-js-express-restapis-using-multer-sequelize-orm

In the tutorial, we show how to upload files, download files from Angular 11 Client to MySQL with Node.js RestAPIs server using Multer middleware and Sequelize ORM.

Related posts:
Node.js/Express RestAPIs server – Angular 11 Upload/Download Files – Multer + Bootstrap
Angular 11 HttpClient Crud + Node.js Express Sequelize + MySQL – Get/Post/Put/Delete RestAPIs

Continue reading “Angular 11 Nodejs/Express MySQL Multer Sequelize – Upload Files/Download Files”

Angular 12 Nodejs MySQL – Upload Files/Download Files using Multer + Sequelize ORM

Angular 12 Nodejs MySQL – Upload Files/Download Files using Multer + Sequelize ORM

https://ozenero.com/frontend/angular/angular-6/angular-6-httpclient-upload-files-download-files-to-mysql-with-node-js-express-restapis-using-multer-sequelize-orm

In the tutorial, we show how to upload files, download files from Angular 12 Client to MySQL with Node.js RestAPIs server using Multer middleware and Sequelize ORM.

Related posts:
Node.js/Express RestAPIs server – Angular 12 Upload/Download Files – Multer + Bootstrap
Angular 12 HttpClient Crud + Node.js Express Sequelize + MySQL – Get/Post/Put/Delete RestAPIs

Continue reading “Angular 12 Nodejs MySQL – Upload Files/Download Files using Multer + Sequelize ORM”