Sending a compressed file via HTTP response using a TypeScript Lambda function in AWS connected to an API Gateway

Looking to send a local zip file over http from an AWS TypeScipt Lambda, as shown below:

exports.handler = async function (event: any) {
   let zip = readZip()
   return {
      statusCode: 200, 
      headers: { "Content-Type": "application/zip", "Content-Dispostion": "attachment; filename=filename.zip" }, 
      body: zip
   }
}

After trying various methods, the closest I got was using fs.readFileSync() to read the zip file, but it resulted in a slightly corrupted file that cannot be unzipped.

Attempts with JSZip and JSZipUtils, decoding base64 strings, and converting byte buffers have all failed. The goal is to directly deliver the file as an APIGateway response without hosting it on an S3 bucket for download.

Any suggestions or insights on how to achieve this successfully?

Answer №1

Alright, here's a simplified explanation of how I tackled this issue:

  1. Firstly, I included the header "'Content-Encoding': 'base64'" in the request
  2. Next, I read the file in base64 format
  3. I then added the parameter "isBase64Encoded: true" to the return statement
  4. It's important to remember to enable binary content in ApiGateway for this solution to work properly

In essence, the content undergoes double base64 encoding - once during reading and again by AWS where the lambda encodes it, followed by decoding by ApiGateway and another round of decoding by the HTTP Client.

Below is how the final code appeared:

exports.handler = async function (event: any) {
   let zip = readZip()
   return {
      statusCode: 200, 
      headers: { 
         "Content-Type": "application/zip, application/octet-stream", 
         "Content-Disposition": "attachment; filename=filename.zip",
         "Content-Encoding" : "base64"
      },     
      body: zip,
      isBase64Encoded : true
   }
}

readZip() function:

const zipFile = fs.readFileSync("filename.zip", "base64")
return zipFile

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

Variations in default export behavior in Webpack when using Typescript versus Javascript

In my React application, I have a page that imports a component from another file. // Code snippet from IconPage.tsx import {AccountBalanceIcon} from './icons'; <AccountBalanceIcon /> // Code snippet from ./icons.ts export { default as A ...

Typescript error code TS7053 occurs when an element is detected to have an implicit 'any' type due to an expression of a different type

I encountered an issue with the provided example. I'm uncertain about how to resolve it. Your assistance would be greatly appreciated. type TestValue = { value: string; }; type FirstTest = { type: 'text'; text: TestValue[]; }; typ ...

Define the type as an array of any attributes from an interface

Looking for a solution: interface Details { id: string; groups: Group[]; name: string; total: number; open: boolean; debug: boolean; demo: boolean; registered: boolean; } I'm seeking a way to create an array type with property names f ...

Tips for resolving the React(TypeScript) issue "Invalid hook call."?

I received an error message stating: "Invalid hook call. Hooks can only be called inside of the body of a function component." within my React function: interface Items { items: any[] } const [items, setItems] = useState<Items>(); const ItemsList ...

What is the best way to enhance my mapbox-gl map in an angular application by utilizing a forEach loop?

I am looking to enhance my map by incorporating multiple features into a single source, rather than just a single line. In my typescript code, I currently have an array called myRoutes that contains all the routes (coordinates for the lines to be drawn). ...

Updating an Angular mat-table when the drawer is located in a separate component: A complete guide

The primary element contains tabs, component A, B, and so on. My component_A comes with preloaded information, but it also includes a filter button. Additionally, there is a button that triggers a drawer from another component (the main component). toggl ...

Remove an item from an array within Express using Mongoose

{ "_id": "608c3d353f94ae40aff1dec4", "userId": "608425c08a3f8db8845bee84", "experiences": [ { "designation": "Manager", "_id": "609197056bd0ea09eee94 ...

Is there a way to extract both a and b from the array?

I just started learning programming and I'm currently working on creating an API call to use in another function. However, I've hit a roadblock. I need to extract values for variables a and b separately from the response of this API call: import ...

Exploring the concept of asynchronous subscriptions in Angular

My current issue seems to be related to asynchronous programming, specifically with the subscription not running at the desired time. I typically approach this problem from both the user's and developer's perspectives. User's Perspective: ...

Can you provide an overview of the ternary operator within advanced method signatures in TypeScript?

I'm struggling to understand the method signature provided below: export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; This code snippet was in response to a question on c ...

Is there a way to stop TSC from performing type checking on projects within the node_modules directory

I'm encountering an issue where tsc is performing type-checking on files within the node_modules directory, resulting in errors like: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="513c287c21233e3b34322511617f617f ...

Starting up a pre-existing Angular project on your local machine

I am completely new to Angular and facing difficulties running an existing project on my machine. Despite conducting numerous tests and following various articles, I still cannot get the project to run. Here is the layout of my project files: https://i.s ...

Angular: What is the best way to retrieve the class name in the app-root from a local component?

My website consists of three main pages and multiple child pages. Each child page inherits its style from the parent CSS. country.routes.ts ... path: '', children: [ { path: '/country', component: CountryComponent ...

How can I capture the click event on the oktext in Ionic?

When using Ionic, I have a select button with options for okText and cancelText. The issue I am facing is that when I click on okText, the menu closes as expected due to this attribute. However, I am interested in implementing it through click events. Belo ...

Guidelines for Effectively Sharing and Managing Typescript Types in Large-Scale Projects across Frontend and Backend

My MERN project has a unique folder structure that includes: backend, which consists of an express mongo backend with the following layout. frontend containing 3 vite react projects, each with their own specific folder setup. Parent Folder: - backend ...

Utilizing Typescript template strings for data inference

In coding practice, a specific convention involves denoting the child of an entity (meaning an association with another entity) with a '$' symbol. class Pet { owner$: any; } When making a reference to an entity child, users should have the opt ...

Efficient approach for combining list elements

I have a collection of content blocks structured like this: interface Content{ type: string, content: string | string[] } const content: Content[] = [ { type: "heading" content: "whatever" }, { type: "para&quo ...

Using a Jasmine spy to monitor an exported function in NodeJS

I've encountered difficulties when trying to spy on an exported function in a NodeJS (v9.6.1) application using Jasmine. The app is developed in TypeScript, transpiled with tsc into a dist folder for execution as JavaScript. Application Within my p ...

Get your hands on a file that's stored within your project - utilizing JavaScript in React

Currently, I am developing a react project with typescript. Within the project directory, there is an excel file in (.xlsx) format that I need to make downloadable from the UI by clicking on a button or link. My research online led me to the <a> tag ...

`Unable to update the checked prop in MUI switch component`

The value of RankPermission in the switchPermission function toggles from false to true, but for some reason, the MUI Switch component does not update in the browser. I haven't attempted any solutions yet and am unsure why it's not updating. I&ap ...