Error message: "An internal server issue occurred while attempting to upload an image in base64 format via AWS Lambda

I've been working on uploading images to S3 using AWS Lambda. I found some helpful code in a URL and made some modifications to the variables fileFullPath and Bucket:
Upload Image into S3 bucket using Api Gateway, Lambda funnction

const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const moment = require('moment');
const fileType = require('file-type');
const sha1 = require('sha1');
const multipart = require('parse-multipart');

exports.handler = function (event, context, callback) {

    let request = event.body;

    // get the request
    let base64String = request.base64String;

    // pass the base64 string into a buffer
    let buffer = new Buffer(base64String, 'base64');

    let fileMime = fileType(buffer);

    // check if the base64 encoded string is a file
    if (fileMime === null) {
        return context.fail('The string supplied is not a file type');
    }

    let file = getFile(fileMime, buffer);
    // let file = getFile(fileMime, parts);
    let params = file.params;

    s3.upload(params, function (err, data) {
    // putObject(params, function (err, data) {
        if (err) {
            console.log(err);
            callback(err);
        }

        // if the file object is uploaded successfully to 
        // s3 then you can get your full url
        console.log('File URL', file.full_path + JSON.stringify(data));
        callback(null, data);

    });
}

let getFile = function (fileMime, buffer) {

    // get the file extension
    let fileExt = fileMime.ext;
    let hash = sha1(new Buffer(new Date().toString()));
    let now = moment().format('YYYY-MM-DD');

    let filePath = hash + '/';
    let fileName = now + '.' + fileExt;
    let fileFullName = filePath + fileName;
    let fileFullPath = 'https://console.aws.amazon.com/s3/buckets/bucket-name/images/' + fileFullName;

    console.log('fileFullPath' + fileFullPath);
    let params = {
        Bucket: 'bucket-name',
        Key: fileFullPath,
        // 'this is simply the filename and the extension, e.g fileFullName + fileExt',
        Body: buffer,
        ContentType: fileMime.mime
    };

    let uploadFile = {
        size: buffer.toString('ascii').length,
        type: fileMime.mime,
        name: fileName,
        full_path: fileFullPath
    }

    return {
        'params': params,
        'uploadFile': uploadFile
    }
}

https://i.stack.imgur.com/EPpdi.png

Execution role for this lambda function: https://i.stack.imgur.com/zbLAc.png

In API Gateway, I only create the resource and method 'POST' and have nothing set in method request section.
I've made a test for this POST method but Internal server error occur: https://i.stack.imgur.com/JyQKi.png

Update: current error got from cloudwatch

The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined

Answer №1

If you are new to working with AWS Lambda, a helpful tip is to check out the CloudWatch logs. Here, you can find the specific errors as well as any output from "console.log(xxx)" statements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verify the presence of a symbolic link in node.js

A common problem arises when dealing with symlinks and the existence of the source file they point to. If the source file no longer exists, but the symlink still does, performing a fs.exists(symlink) check will return false. Consider this test scenario: ...

Curious about how to utilize Gridfs to upload files or videos larger than 16mb with the help of express, mongoose, and mongodb?

I'm encountering an issue with my code. It works fine for uploading images, but when I try to upload videos or files larger than 16mb, it fails. I am a beginner and seeking help on what to do next. const Freecoursevideo = require("../models/freec ...

Calculating the total of fields from populated documents using Mongoose

In my application, I have two main models: User and Track. A User can complete various Tracks and earn points for each one. The schema for the User model looks like this: let userSchema = new mongoose.Schema({ name: {type: String, required: true}, ...

Encountering a cross-origin resource sharing (CORS) error while attempting

My Vue App is being hosted on an express server (nodejs running on port 60702) with the following setup: 'use strict'; const fs = require('fs'); const path = require('path'); const express = require('express'); var h ...

The node command line does not recognize the term 'require'

My Typescript project was compiling and running smoothly until recently when I started encountering the error ReferenceError: require is not defined every time I try to run node. I am uncertain whether this issue stems from Typescript, as even when I ru ...

Delay the next loop iteration until receiving an HTTP request

I have a task where I am collecting YouTube video IDs and storing them in an array. Then, I am looping through each video ID to determine the size of that ID's thumbnail image. My challenge now is making sure my loop waits for the HTTP request to fini ...

Successful build of node app, however, not appearing on Heroku for MEAN Stack application

After numerous failed attempts, I finally managed to successfully build and deploy my app on Heroku. However, when I tried to access it, all I got was an 'Application error'. The log for the successful build is as follows: -----> Node.js app d ...

Passing a response from a combination of asynchronous and synchronous functions in a provider script to an Express server

Forgive me for bringing up this issue - I know there is an abundance of information on async functions available, but despite trying various approaches, I am unable to find a solution... To provide some context, let me describe the setup of my program. It ...

Ensure that an HTTP post request is successfully completed before proceeding to execute the next HTTP post request within a loop

I have a loop that sends a HTTP post request each time it iterates. for(let i = 1; i < this.data.length; i++) { let arr = this.data[i]; this.http.post('link here', { name: arr[0], gender: arr[1], course: ar ...

The nested dependency in npm is not up-to-date

Within the structure of my Node.js project, I rely on a dependency called gulp, which in turn relies on another dependency named vinyl-fs. This chain continues with vinyl-fs depending on glob-watcher, and finally, glob-watcher relying on gaze. It should be ...

Exploring Azure: Obtain a comprehensive list of application settings from a deployed Node.js web application

After successfully deploying a NodeJs app to a Linux Azure AppService, I am now aiming to retrieve the server settings of this particular app-service. By enabling managed Identity for the AppService under the 'Identity' tab, I attempted to achiev ...

The error message "Cannot read property 'find' of undefined in mongodb" indicates that there is an issue with

Currently in the process of integrating mongoose into a nodejs project. Took the step to create a test record within a collection for the purpose of testing out CRUD operations from the backend, specifically interested in trying out the find() property of ...

Is it possible to import from the root directory using native ES modules in Node.js version 16?

Here is the structure of our project: - project - a.js - b.js In a.js, I am looking to import the b.js file using the root path in this manner: import c from '~/b.js'; Instead of using a relative path like this: import c from '.. ...

Dealing with undefined or null values when using ReactJS with Formik

Issue Resolved: It seems that Formik requires InitialValues to be passed even if they are not necessary. I'm currently working on a formik form in React, but every time I click the submit button, I encounter an error message stating "TypeError: Canno ...

Strange Actions of Mongoose and Everyauth

Whenever a new user logs in to my website using everyauth for the first time, the following code is executed. It checks if the user exists in my mongodb database and if not, it creates a new entry. However, I am facing an issue where this process works p ...

Redirect all subdomains to corresponding folders with matching names

I am working on an Express app and I have the requirement to route each subdomain to its corresponding folder in the filesystem. To illustrate, when a GET request is made to example.com, it should look for files in the root folder ./, whereas blog.example. ...

No response is generated by Express upon completion of bulk insertion

Looking to efficiently insert data in mongodb using mongoose. The data is being saved in the database without any issue, but there seems to be an issue with sending a response back from express. We have tried methods like insertMany and bulkWrite try { ...

Updates to Mongoose validators have not been implemented

I am currently using the mongoose library along with the npm package called "mongoose-unique-validator" to handle validation in my application. Initially, I had no issues integrating it into my schema and it worked perfectly fine. However, I recently made ...

Utilizing the power of an Alexa Skill to generate an organized To-Do list with predefined tasks

Currently, I'm developing an innovative Alexa Skill that allows users to say: "Alexa, ask _____ what items should I bring for my trip?" and she will reply with "You should bring x, y, z. I made a to-do list in your Alexa App with these items". The go ...

Unable to render pages with ng-view in Angular.js

I am facing an issue with my Angular.js application where the pages are not loading when using ng-view. When I type the URL http://localhost:8888/dashboard, the pages should be displayed. Here is an explanation of my code: view/dashboard.html: <!DO ...