Access both uploading and downloading of files using a single API gateway with pre-signed URLs

Need help with the following functionalities:

  1. Connecting the output of a lambda function (presignedURL) to an API gateway;
  2. Sending the presignedURL to the user's browser for triggering a download.

Imagine a scenario where a user uploads a csv file through an API to s3. A lambda function then processes the data and sends a pdf file back to the user's browser.

I am looking for assistance with implementing a download function in the provided app.js that integrates with the uploading feature of the AWS API Gateway. Any suggestions on how to include the aforementioned functionalities would be greatly appreciated!

  • Transferring the output of the lambda function (presignedURL, within 30 seconds) to the API gateway;
  • Sending the presignedURL to the user's browser to trigger a download.

// Code snippet for uploading function

const AWS = require('aws-sdk')
AWS.config.update({ region: process.env.AWS_REGION })
const s3 = new AWS.S3()

const URL_EXPIRATION_SECONDS = 300

// Main Lambda entry point
exports.handler = async (event) => {
  return await getUploadURL(event)
}

const getUploadURL = async function(event) {
  const Key = `test.csv`

  // Obtain signed URL from S3
  const s3Params = {
    Bucket: process.env.UploadBucket,
    Key,
    Expires: URL_EXPIRATION_SECONDS,
    ContentType: 'text/csv',

    // Setting ACL to make the uploaded object publicly readable is necessary. Don't forget to uncomment
    // the additional permission for the Lambda function in the SAM template.

    // ACL: 'public-read'
  }

  console.log('Parameters: ', s3Params)
  const uploadURL = await s3.getSignedUrlPromise('putObject', s3Params)

  return JSON.stringify({
    uploadURL: uploadURL,
    Key
  })
}

// Download function (pdf)

const Downloadfunc ...
   
    // Retrieve presignedURL from lambda function output

    // Transmit presignedURL to the user's browser to initiate a download
... 

      </div>
      <h2 v-if="uploadURL">File uploaded to bucket.</h2>
    </div>
  
    <script>

      const API_ENDPOINT = 'https://*****.execute-api.us-east-1.amazonaws.com/uploads'
      
 ...

Answer №1

It is impossible for the lambda function to directly communicate with the API gateway in the way you want it to. The lambda is triggered by S3 and does not have knowledge of the API gateway, just as the API gateway does not have knowledge of the specific lambda execution.

To achieve your goal, you could design the lambda to save the uploaded file using a consistent naming pattern, such as appending .pdf to the original filename or assigning a UUID. Then, users can call a download function that checks if the PDF already exists and provides a presigned URL for download, or displays an error message if the file is not yet available.

Alternatively, you could implement a database to store information about the location of the target file while keeping the rest of the logic unchanged.

Regardless of the approach chosen, there needs to be a way to identify the file, whether through a UUID assigned during upload or as part of the file's name. Clients can then use this identifier to request a download once the server has completed processing.

Another option could be to utilize websockets to notify the client when the upload process is complete, but this essentially achieves the same result in a more sophisticated manner.

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

Handling the display of divs using two select elements

I've been pondering this problem for a while now, and I'm starting to believe that there may not be a solution. Essentially, what I am trying to achieve is the ability to select options from two dropdown menus which will then show or hide specifi ...

Unable to retrieve $scope.property using direct access, however it is visible when printed to the console using console.log($

I have successfully populated $scope with data using a get call: httpGetAsync("myUrlWasHere", getBlogPosts, $scope); The console outputs the data when I print console.log($scope): https://i.sstatic.net/SkDl9.png However, when I try to access it using c ...

Execute a function upon pressing the enter key

Currently, I am working on coding a webpage with a form that includes one field where users input a set of numbers. After typing in the numbers, they should then press a button labeled 'Run' to execute the code. However, the issue arises when use ...

Leverage the power of JavaScript functions within the app.component.ts file of

I have a JavaScript file named action.js and I am trying to incorporate it into an Angular project. After doing some research, I found out that the js file should be placed in the assets folder and the path must be referenced in the scripts array within an ...

The websocket connection to the production host has encountered issues, while it operates smoothly on localhost within Django

I successfully integrated a websocket connection for real-time updates in my Django application. The issue arises when I try to host the application on a public server, as it fails to connect. I am using Daphne server for hosting. Below is a snippet of my ...

How to display a Bootstrap modal when clicking on buttons within a dynamic loop of <li> tags?

I would like to share a problem I am facing with buttons in 'li' tag loop. When the info button is clicked, a particular modal should open. However, after clicking the button, the modal does not pop up on screen even though the EJS loop is functi ...

How to Determine the Size of a JSON Response Using JQuery?

When using a JQuery getJSON call, how can I determine the length of the JSON data that is returned? function refreshRoomList() { $.getJSON('API/list_rooms', function (rooms) { if (rooms.length > 0) { ...

Having trouble with a jQuery.validationEngine reference error?

Despite everything being correctly referenced, I am facing difficulties in getting it to function properly. It's strange because it worked once, but the validation message took 10 seconds to appear. After that, without making any changes, I tried agai ...

Guide on generating a route using coordinates in a threejs environment

Currently, I am working with an array of coordinates obtained from the Google Maps Navigation API. I have successfully plotted these coordinates on a sphere, however, my objective is to extract the shape of the path by combining all the coordinate points ...

Having difficulty accessing the persisted state value through redux-persist once the store has been rehydrated

Imagine you have a Home Component that simply makes an api call to retrieve all homeworks from the server: import React, { Component } from 'react'; import { fetchHomeWorks } from '../actions'; import HomeWorkRow from '../componen ...

Update input field value with data retrieved via ajax call in AngularJS

My current approach involves using AngularJS directives for Bootstrap in order to create an edit form on a Bootstrap modal when the user clicks on the edit button from a list of items. Here is the code I have implemented: HTML: <div class="modal-heade ...

Utilize JavaScript to dynamically modify the position of an HTML element

I am working on a script that can manipulate the size of a period symbol, making it increase and decrease in size while staying in one place. However, I have encountered an issue where the element moves up or down the page when its size changes. I tried ...

Decoding the JSON response object

Upon receiving a JSON response from an Ajax call, I handle it in the following way: oData = JSON.parse(sReply); Within this code snippet, we have the object definition as follows: var oData = new cData(); function cData() { this.Email = ""; thi ...

Incorporate a Three.js viewer within a WPF application

I am currently exploring the use of Three.js to develop a versatile 3D renderer that can run seamlessly on various platforms through integration with a "WebView" or "WebBrowser" component within native applications. I have successfully implemented this sol ...

Creating dynamic web content using KaTeX and Node.js

When I attempt to display a complex formula using HTML and CSS, I encounter difficulties. Instead of the desired output, my screen is filled with confusing unicode characters. To resolve this issue, I decided to use KaTeX. I downloaded KaTeX into the dire ...

Create a token for

Visit this link for more information on listing functions in Azure web apps https://i.sstatic.net/YgsF5.png Is there a way to dynamically generate the green-highlighted token using JavaScript or an API? While I'm aware that the token can be generate ...

Experimenting with protractor to test UI-bootstrap-alert components

I am currently working on using protractor to verify the correct display of alerts. Below is an excerpt from one of my spec files. The HTML code snippet looks like this: <div class="alert ng-scope floater bottom left fadeZoomFadeDown alert-success" n ...

Constructing an Http Post URL with form parameters using the Axios HTTP client

I need assistance in creating a postHTTP request with form parameters using axios on my node server. I have successfully implemented the Java code for constructing a URL, as shown below: JAVA CODE: HttpPost post = new HttpPost(UriBuilder.fromUri (getPro ...

Inquire about the width of the SVG text element

I am working with an SVG text element that looks like this: <text data-model-id=​"k10673" x=​"584" y=​"266" fill-opacity=​"1" style=​"font:​ 12px Arial,Helvetica,sans-serif;​ " fill=​"#a5d16f">​BU YIL SONU​</text>​ The t ...

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, ...