Can a File Object be transmitted to an AWS Lambda function via API Gateway using JavaScript?

Can a JavaScript File Object be passed from a browser to AWS Lambda via API Gateway (ultimately to S3)? I am working with TypeScript and React.

Environment

Frontend

  • TypeScript
  • React
  • AWS Amplify (for API module)

Backend(AWS Lambda)

  • Node.js

Expectations

The goal is to send the File Object, obtained from the browser using <input type='file'>, to the backend AWS Lambda through API Gateway.

Current Situation

When doing a console.log(event) in the backend, the log output comes out empty.

What I Would Like to Know

I am looking for guidance on how to correctly pass the File Object (Blob) to lambda. A link to documentation would greatly help me.

Code (Frontend)

import { API } from 'aws-amplify'
...
const file = { body: this.state.file }
console.log(file) // correctly capturing the File Object at this point
API.post(<API_NAME>, <PATH>, file)
  .then(response => {
    console.log(response)
  }).catch(error => {
    console.log(error)
  })

Code (Backend)

exports.lambdaHandler = function (event, context, callback) {
  console.info(`event.body: ${event.body}`) // receiving `event.body: {}` in Cloud Watch Logs
  ...
}

Is it possible to achieve my objective by setting Content-Type or another method? (I have not been able to find relevant documentation as I only started programming a year ago).

Answer №1

I have a different viewpoint compared to sidali's answer, citing concerns such as security and cost implications. It is not advisable to have an S3 bucket that is publicly accessible.

Instead, it is recommended to generate a presigned URL for S3 through your API Gateway + Lambda. This way, only the authorized user can upload a file within a specified timeframe (e.g., 1 minute or 5 hours).

const getSignedUrlForUpload = async () => {
  const params = {
    Bucket: BUCKET_NAME,
    Key: 'AWS_Cloud_Best_Practices.pdf',
    Expires: 60,
    ContentType: 'application/pdf',
  }


  const url = await new Promise((resolve, reject) => {
    s3.getSignedUrl('putObject', params, (err, url) => {
      if (err) reject(err)

      resolve(url)
    })
  })

  return url
}

uploadFileToS3()
  .then((res) => {
    console.log(res)
  }).catch((e) => {
    console.log(e)
  })

Source:

Answer №2

To securely upload your file directly to a specific Bucket on s3, you need to create a lambda trigger event for when the file is uploaded to that particular Bucket.

By setting up this trigger, lambda will be activated every time a file is sent, allowing you to then read and process your file accordingly.

For more detailed instructions, please refer to this link

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

When using window.open in Chrome on a dual screen setup, the browser will bring the new window back to the

When using the API window.open to open a new window with a specified left position in a dual screen setup (screen1 and screen2), Chrome behaves differently than IE and FF. In Chrome, if the invoking screen is on the right monitor, the left position always ...

Prompt for confirmation in ASP.NET code-behind with conditions

I've searched around for a solution to this problem. Below is a representation of my pseudocode: bool hasData = ItemHasData(itemid); Confirm = "false"; // hidden variable if (hasData) { //Code to call confirm(message) returns "true" or "false" ...

Can anyone point out where the mistake lies in my if statement code?

I've encountered an issue where I send a request to a page and upon receiving the response, which is a string, something goes wrong. Here is the code for the request : jQuery.ajax({ url:'../admin/parsers/check_address.php', meth ...

Error encountered: Element cannot be clicked on at specified coordinates - Angular/Protractor

Recently, I have been testing out CRUD functionality in an Angular app using Protractor. One recurring issue I've encountered is with the create/edit buttons, which all open the same modal regardless of the page you're on. The frustrating part i ...

Using custom hooks in JSX triggers a TypeScript error when the returned component is accessed

i just created a custom hook // useDropdown.ts function useDropdown(defaultState: number, options: number[]) { const [state, setState] = useState(defaultState); function Dropdown({ name }: { name: string }) { return ( <> <sel ...

There seems to be an issue with the performance of Google script .setFormula when used in conjunction with the

Hello everyone, I have written a script that inserts formulas in a specific range and set up a trigger for it to run between 01:00 and 02:00 AM. The purpose is to subscribe the values with the formulas and then paste the resulting values. However, I am fac ...

Manipulate the value(s) of a multi-select form field

How can you effectively manage multiple selections in a form field like the one below and manipulate the selected options? <select class="items" multiple="multiple" size="5"> <option value="apple">apple</option> <option va ...

Find the total number of table rows that exist between two specific rows using jQuery

<table> <tr id="family_1"> <td>Family 1</td> </tr> <tr class="member"> <td>Member 1</td> </tr> <tr class="member"> <td>Member 2</td> </tr> ... <tr ...

``Can you help me understand how to display two different values in the same field

import React, { Component } from 'react' import DatePicker from 'material-ui/DatePicker'; class CombinedDateField extends Component { state = { first:'', second:'', } handleChangeFirstEventDate = (event, ...

Choose a procedure to reset to the original setting

I'm attempting to achieve something that seems straightforward, but I'm having trouble finding a solution. I have a <select> tag with 5 <option> elements. All I want to do is, when I click a button (which has a function inside of it), ...

How to open a new tab in ReactJS

When attempting to open a component in a new tab using the Link in React router, it results in a 404 error page being displayed instead of the desired react component. The main React entry point file (js), import React from 'react'; import { re ...

Ensure that the radio is turned on by clicking the button or selecting the radio option

Is it possible to create a radio button within a button using mui, where the user can click on either the radio button or the button to check it? The user should only be able to choose one option - either female or male. Instead of using multiple use stat ...

Angular Validators.pattern() does not seem to function properly, despite yielding successful results in online regex testers

I have developed a regex pattern on Regex101.com and thoroughly tested it. However, when I applied it to my FormControl Validators.pattern method, it is exhibiting unexpected behavior. This regex pattern is meant for validating the Width input of a packag ...

AngularJS Component enthusiasts

While going through a tutorial on the Angular UI Router GitHub page (link: https://github.com/angular-ui/ui-router), I came across an intriguing code snippet: var myApp = angular.module('myApp', ['ui.router']); // For Component users, ...

AngularJS - retrieving and displaying the selected value from an HTML dropdown menu

Could someone help me figure out why the Land selection is empty when trying to display it as {{ selectCenter.land }}? For reference, here is a functional plunker: http://plnkr.co/edit/Q8jhdJltlh14oBBLeHJ9?p=preview And the relevant code snippet: ...

What is the correct method for orchestrating API requests during deployment with create-react-app and an ExpressJS backend?

I have encountered a problem while trying to deploy my react application to the server. After deployment, when the app attempts to make API calls to the same server, an error occurs: Cross-Origin Request Blocked: The Same Origin Policy disallows reading ...

Utilizing Next.js to create a Higher Order Component (HOC) for fetching data from a REST API using Typescript is proving to be a challenge, as the

In my withUser.tsx file, I have implemented a higher order component that wraps authenticated pages. This HOC ensures that only users with a specified user role have access to the intended pages. import axios, { AxiosError } from "axios"; import ...

What is causing .then() to not wait for the promise to resolve?

I'm currently delving into an Angular project, and I must admit, it's all quite new to me. My confusion lies in the fact that the .then() function doesn't seem to be waiting for the promises to resolve. Could this have something to do with ...

Explaining the process of defining an object type in TypeScript and the conversion from JavaScript

Currently, I am attempting to enhance the background of a React website developed in typescript (.tsx) by incorporating particles. My approach involves utilizing the particle-bg component available at: https://github.com/lindelof/particles-bg However, whe ...

Sending a parameter to a different function (on a separate webpage)

At the start of my webpage, there are two radio buttons on the first page, each with its own value. Upon clicking a link to move to the second page, a for loop is activated to grab the value of the selected button. The script has been tested and works as e ...