Share your base64 encoded image on imgur platform

I am encountering an issue while attempting to upload a base64 encoded image from https://pastebin.com/1ereVVqh to imgur. The error message I keep receiving is as follows:

HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "OK", url: "https://api.imgur.com/3/image", ok: false, ...}
error:
data: {error: "Invalid URL (data:image/jpeg;base64,/9j/4AAQSkZJRg…CGmGI2nNxt/MW7l/qMleILRMoczAlq57S8Ia6HQg3UY5Z//Z)", request: "/3/image", method: "POST"}
status: 400
success: false
__proto__: Object
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for https://api.imgur.com/3/image: 400 OK"
name: "HttpErrorResponse"
ok: false
status: 400
statusText: "OK"
url: "https://api.imgur.com/3/image"
__proto__: HttpResponseBase

The code I am using is shown below:

upload.controller.ts

  handleFileInput(e) {
    const reader = new FileReader();
    if (e.target.files && e.target.files.length) {
      const [file] = e.target.files;
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.imgurService.upload(reader.result, this.user.uid).subscribe((imgurResponse: ImgurResponse) => {
          this.logger.debug(imgurResponse);
        });
      };
    }
  }

imgur.service.ts

  upload(base64Img: any, uid: string) {
    this.logger.debug('Handling file input');
    this.logger.debug(base64Img);
    this.logger.debug(`Uploading picture to ${this.IMGUR_UPLOAD_URL}`);
    const headers = new HttpHeaders().set('Authorization', `${this.IMGUR_CLIENT_ID}`);
    const formData = new FormData();
    formData.append('image', base64Img);
    formData.append('name', uid);
    formData.append('type', 'file');
    return this.http.post<ImgurResponse>(`${this.IMGUR_UPLOAD_URL}`, formData, { headers });
  }

Does anyone have any insights into why this setup is not functioning as intended?

Answer №1

As per the documentation from the imgur API, the type should be specified as base64 in your situation: (or maybe even URL for base64 encoded URI, you need to experiment to determine which one)

Image Upload
Upload a new image.

Method  POST
Route   https://api.imgur.com/3/image
Alternative Route   https://api.imgur.com/3/upload
Response Model  Basic
Parameters
Key Required    Description
image   required    A binary file, base64 data, or a URL for an image. (up to 10MB)
album   optional    The id of the album you want to add the image to. For anonymous albums, {album} should be the deletehash that is returned at creation.
type    optional    The type of the file that's being sent; file, base64 or URL
name    optional    The name of the file, this is automatically detected if uploading a file with a POST and multipart / form-data
title   optional    The title of the image.
description optional    The description of the image.

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 you compile TypeScript with the target set to 'ES3' or 'ES5', it creates an internal structure

Recently delved into the world of TypeScript and experimenting with webpack ts-loader and babel-loader to compile and transpile TypeScript into ES5. However, I came across a compiler option in tsc that can target 'ES5', which made me question the ...

Retrieving array-like form data in a TypeScript file

I need assistance with passing form inputs into a typescript file as an array in an ionic application. The form is located in question.page.html <details *ngFor="let product of products;"> <ion-input type="text" [(ngModel ...

Enhancing Vue prop with TypeScript typing

In my Vue component, I am working with a prop called tabs. The format for this prop is expected to be as follows: [{ id: string title: string color: `#${string}` },{ id: string title: string color: `#${string}` }] Currently, I am utilizing Lar ...

Can TestCafe be used to simulate pressing the key combination (Ctrl + +)?

I've been having a tough time trying to use the key combination specified in the title (Ctrl + +). So far, this is what I've attempted: 'ctrl+\+' 'ctrl+\\+' Does TestCafe even support this key combination? T ...

Generate a collection of elements using a different collection as a reference

I am struggling with an array of objects: let data = [{ createdDate: "2222", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087c6d7b7c3d487c6d7b7c266b6765">[email protected]</a>", histories: [ ...

The pagination feature in ag-grid is malfunctioning, causing it to initially send a request to

Upon clicking the search button, a server call will be made to retrieve results and display them in the ag grid. The server will only return the specified number of records based on the pagination details provided with each click. Despite implementing the ...

Type guard does not narrow down the union type

Explore the following code snippet: type UnionType = 'foo' | 'bar' | 'baz' const obj = { foo: 'huh', bar: 'hmm' } function func(input: UnionType) { if(input in obj) { input } } In ...

The bottom of the page displays varying outcomes between Code Snippet (CodePen) and Angular

I had the idea of having my footer cover the entire length of the page and stick to the bottom, adjusting itself if more content is added. However, I encountered an issue where on Codepen everything works perfectly, but on Angular (14), the footer does not ...

When running the command ng build --prod, it seems that the module for class X cannot be determined. To resolve this issue, make sure to include

I'm encountering an issue while trying to develop my Angular 5 application. The error message reads: Cannot determine the module for class ThreadListTabsComponent in /home/brightwater/Differ/src/app/thread-lists/thread-lists.component.ts! Add T ...

Running ngAfterViewInit() code in Angular should be done only after Inputs() have been initialized

Within a particular component, I have implemented some code in ngAfterViewInit: @Input public stringArray: string[]; public newArray: string[]; ngAfterViewInit() { this.newArray = this.stringArray.filter(x => x.includes('a')); } I placed ...

The npm installation process has come to a sudden halt

Starting a web application in Angular 17 has been my goal. I typically run npm install followed by ng serve. However, this process suddenly stopped working. To troubleshoot, here are the steps I've taken: Updated npm to the latest version (10.2. ...

The problem with uploading files in Angular4 (with multer on the server)

In my current project, I encountered an issue where the front end file was not getting transferred to the server side after finishing both the front end and back end logic. Despite spending more than an hour debugging, I couldn't pinpoint the exact ca ...

The response code in the API remains 200 despite setting the status code to 204 in NestJS

I have developed an API that needs to return a 204 - No Content Response import { Controller, Get, Header, HttpStatus, Req, Res } from '@nestjs/common'; import { Response } from 'express'; @Get("mediation-get-api") @Head ...

Ways to initiate a language shift in the **JavaScript yearly calendar** when the language is modified in an Angular application

1. I have incorporated ngx-translate into my Angular application for translation purposes. 2. I have successfully implemented the ability to switch languages during initialization by specifying options like {language:'ja'} for Japanese within th ...

Vercel seems to be having trouble detecting TypeScript or the "@types/react" package when deploying a Next.js project

Suddenly, my deployment of Next.js to Vercel has hit a snag after the latest update and is now giving me trouble for not having @types/react AND typescript installed. Seems like you're attempting to utilize TypeScript but are missing essential package ...

Utilize NodeJS and Typescript to input data into a postgreSQL database

Here is my code snippet: signup.post('/signup', urlendcodedParser, async(req: Request, res: Response) => { const username = req.body.username; const password = req.body.password; const age = req.body.age; const email = req ...

MUI Chips serving as selectible tags with checkbox-like functionality

I have retrieved data from a JSON file containing information about different types of chips: [ { "id": "4", "name": "Caucasian" }, { "id": "5", "name": "Asian" }, ...

Determine if Toggle Accordion is Expanded by Checking HTML Attribute Using Selenium

I am working with an HTML Angular Material Accordion component. When it is expanded, the class mat-expanded is added. <mat-expansion-panel _ngcontent-ng-cli-universal-c931="" data-qa="product" class="mat-expansion-panel ng- ...

How can I turn off the draggable feature for a specific element in react-beautiful-dnd?

Currently, I am implementing a drag and drop functionality using TypeScript with react-beautiful-dnd. The goal is to allow users to move items between two containers - one containing user names and the other labeled "Unassigned". Here is a snapshot of the ...

The useEffect hook in React is signaling a missing dependency issue

Any tips on how to resolve warnings such as this one src\components\pages\badge\BadgeScreen.tsx Line 87:6: React Hook useEffect has a missing dependency: 'loadData'. Either include it or remove the dependency array react-hoo ...