Uploading images to an S3 bucket in base64 format using Angular 7

Within my Ionic 4 Angular 7 application, I am attempting to upload an image captured using the Cordova camera plugin.

The output data from this Camera plugin is in the form of base64 image data.

this.camera.getPicture(options).then((imageData) => {
  // imageData can be either a base64 encoded string or a file URI
  // If it's base64 (DATA_URL):
  const base64Image = 'data:image/jpeg;base64,' + imageData;

  this.uploadImage(url, base64Image )
}, (err) => {
  // Handling any errors that may occur
}); 

To achieve this, I am generating a pre-signed AWS S3 URL for uploading images on the server.

For example

The current code does not throw any errors, but after uploading, the image displayed is just a black screen instead of the actual image.

I am looking for the correct method to perform an HTTP PUT request to S3 with the available image content in base64 encoded format.

uploadImage(url: string, imageData: any): Promise<any> {
    const headers = new HttpHeaders({'Content-Type': 'image/jpeg;'});

    return this.http.put(url, imageData, {headers: headers})
        .pipe(
            tap(data => console.log(JSON.stringify(data))),
            catchError(this.handleError('uploadImage'))
        ).toPromise();
}

Answer №1

When I successfully uploaded data using Postman by selecting binary data, I decided to replicate the process in Ionic 4 with HttpClient by referring to sources like:

Angular 5 HttpClient post raw binary data
Convert a binary NodeJS Buffer to JavaScript ArrayBuffer
https://github.com/aws/aws-sdk-js/issues/2141

Here are the steps I followed:
1. Install : npm install buffer
2. Update tsconfig.app.json to include types": ["node"] in "compilerOptions"
3. Add (window as any).global = window; in src/app/pollyfills.ts

uploadImage(url: string, contentType: string, imageData: any): Promise<any> {
    const headers = new HttpHeaders();
    if (contentType === 'jpeg') {
        headers.set('Content-Type', 'image/jpeg;');
    } else if (contentType === 'png') {
        headers.set('Content-Type', 'image/jpeg;');
    }

    const data = imageData.replace(/^data:image\/\w+;base64,/, '');
    const buff = new Buffer(data, 'base64');

    return this.http.put(url, buff.buffer, {headers: headers})
        .pipe(
            tap(data => console.log(JSON.stringify(data))),
            catchError(this.handleError('uploadImage'))
        ).toPromise();
}

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

Modifying input values in AngularJS/HTML

I'm encountering an issue with the ng-repeat function in AngularJS within my HTML code. The problem is that when I change the input with the ID 'add-price' in one cartproduct, it simultaneously changes in all other cartproducts as well. For ...

Exploring the Scope of React Functional Components

My current dilemma involves a React Functional Component acting as a video player. I'm facing an issue where I need to invoke a function named onEnded when the video player triggers its ended event. This function takes in two parameters: a callback pa ...

Display the tooltip and highlight a specific pie slice when clicking on the legend of a pie chart in HighCharts

Hello everyone! I am looking for a way to display tooltips with legends on mouse hover and click events of a pie chart, similar to when hovering over pie slices. Additionally, I want the selected pie slice to slide out upon selection. Currently, I am usin ...

Navigating through this object with PUG and Express: a step-by-step guide

I am currently working on a basic blockchain project to practice my skills with nodejs. I have created a blockchain object that consists of a block class, and now I want to loop through this object using pug. app.get('/', function(request, respon ...

Utilize JavaScript to Extract Information from an Array of JSON Objects

Struggling to efficiently handle an array of JSON objects using JavaScript. The data fetched from my PHP file looks like this: Array ( [0] => Array ( [id] => 1 [name] => holly [text] => Text 1 ...

Cloud Function scheduler incorporating dynamic memory allocation control

I am currently working on setting up a scheduled function in Firebase Cloud Functions that interacts with third-party APIs. However, I am facing an issue with the memory limit being exceeded due to the large size of the data processed by this function. Al ...

How to use jQuery to extract a JSON snippet from a lengthy string

I received an AJAX response in the form of a lengthy string, which includes HTML and JSON data. The JSON object is embedded within the string and not always at the end. My goal is to extract the JSON object from the string so that I can utilize it with th ...

Angular template error: Potential is present but not defined

Encountering an issue with my Angular application's template file (dashboard.component.html). The error message reads "Object is possibly 'undefined'." Here's the portion of the template that seems to be causing the problem: <div> ...

In Typescript, what sets apart a generic written before a function compared to after a type declaration?

Can you explain the difference between these two type declarations for arrow functions? export type Sort = <D>(r: Rows<D>, f: Field<D>, o: Order) => Rows<D>; export type Sort<D> = (r: Rows<D>, f: Field<D>, o: ...

Ways to recycle the table feature in angular2?

I am new to Angular2 framework and I am looking to efficiently reuse a single table component across my entire application. However, I am encountering challenges when it comes to displaying arrays in the table rows. How can I iterate through any type of ar ...

Dismiss the necessity of imports in Angular

I am facing an issue with using a library in Angular, specifically the cubing npm package. This library is designed to run in both the browser and node environments, with specific code for each. I want it to run in the browser, but when compiling with Angu ...

Is it possible to dynamically override inline styles?

My HTML code is as follows: <div title="remove css"style="position:relative;">Remove my style</div> After the page loads, I need to completely remove the position style attribute. Due to limitations, I cannot override the CSS. Is there a way ...

Expanding the Mui Typescript breakpoints within a TypeScript environment

Encountering a typescript error when attempting to utilize custom names for breakpoint values: Type '{ mobile: number; tablet: number; desktop: number;}' is not compatible with type '{ xs: number; sm: number; md: number; lg: number; xl: numb ...

What significance does the dollar sign hold within node Modules?

I've been researching online but I can't seem to find any concrete information. Can someone explain the purpose of the '$' symbol in node modules? For instance, in this code snippet, it's being used extensively: Dashboard Control ...

Encountered an error: Incorrect decomposition attempt on a non-iterable object

I have implemented a DataTable component using react-table. Below is the code for my component: const DataTable: React.FC<IDataTable<any>> = (props: IDataTable<any>) => { const { columns, data, className, rowSelection, onChange, ...r ...

The Sanity npm package encounters a type error during the build process

Recently, I encountered an issue with my Next.js blog using next-sanity. After updating all npm packages, I found that running npm run build resulted in a type error within one of the dependencies: ./node_modules/@sanity/types/lib/dts/src/index.d.ts:756:3 ...

Parsing JSON data using a regular expression

Within my JavaScript file lies a plethora of object literals: // lots of irrelevant code oneParticularFunction({ key1: "string value", key2: 12345, key3: "strings which may contain ({ arbitrary characters })" }); // more irrelevant code My ta ...

Verify the Absence of an Internet Connection Through a Popup on a Windows 10 Application Developed in Javascript

Hey there, I've been browsing the web but can't seem to find a comprehensive tutorial on how to write a code that displays an error message when there is no internet connection. I'm currently using Visual Studio to develop a Windows 10 App w ...

Express 4: Is there a way to upload a file directly to memory, such as storing it as a UTF-8 string, instead of saving it to

I am working on an Express 4 application that requires processing data files uploaded by users and generating an output. These files are not very large (1-2 MB), so I would prefer to upload them directly into memory (e.g. as a UTF-8 string variable) instea ...

Adding custom type definitions for an untyped npm module in TypeScript 2

Despite attempting various methods recommended in other sources, I am struggling to configure a TypeScript project that utilizes an untyped NPM module. Below is a simplified example along with the steps I have taken. Let's imagine, for this demonstra ...