Employ the ctrl-v function to insert images directly into an input file

I am encountering an issue with using an input and a function to paste images.

When I copy the URL of the image and paste it into the input using ctrl-v, I see the URL successfully.

However, if I try to copy the actual image and paste it, ctrl-v does not work and my pasted data is empty.

Does anyone have a solution for making this work for both scenarios, where I can paste the image address or the image itself successfully?

DEMO

CODE

@HostListener('paste', ['$event'])
  onPaste(e: ClipboardEvent) {
    let clipboardData = e.clipboardData || (window as any).clipboardData;
    let pastedData = clipboardData.getData('text');
    alert(pastedData)
}

Answer №1

The issue arises from the different types of data being pasted. One type comes in as a link in text format, while the other is in the form of a file. It is crucial to address each scenario accordingly by detecting the type of data and branching out logically from there.

Chances are, you will need to convert these elements into a blob format. Luckily, for images, the browser handles this conversion automatically. You can find plenty of sample code that demonstrates how to convert a base64 encoded image into a blob, so you should be covered in that aspect as well. Of course, you will need to account for cases where the pasted data is not base64 encoded image urls, but rather random, irrelevant text mistakenly copied by the user.

onPaste(e: ClipboardEvent) {
  const clipboardData = e.clipboardData || (window as any).clipboardData;
  const items: DataTransferItem[] = Array.from(clipboardData.items);
  const textData = items.find(x => x.type === 'text/plain');
  const imageData = items.find(x => /image/i.test(x.type) );
 let blob$: Observable<Blob>;
  if (imageData) {
    blob$ = of(imageData.getAsFile());
  }
  else if (textData) {
    // bindCallback throws error when passing textData.getAsString directly
    const callbackFunc = x => textData.getAsString(x);
    blob$ = bindCallback(callbackFunc)().pipe(
      tap(x => console.log(x)),
      map(/** convert to blob **/)
    );
  }
  else {
    blob$ = of(undefined);
  }
  blob$.pipe(/* do stuff with your blob. */).subscribe();
}

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

The ViewChild from NgbModalModule in @ng-bootstrap/ng-bootstrap for Angular 6 is causing the modal to return as

I have successfully integrated ng bootstrap into my project, specifically utilizing the modal module to display a contact form. The form includes input fields for email and message, as well as a submit button. You can find the ngbootstrap module I am using ...

Sentry: Easily upload source maps from a nested directory structure

I am currently developing a NextJs/ReactJs application using Typescript and I am facing an issue with uploading sourcemaps to Sentry artefacts. Unlike traditional builds, the output folder structure of this app mirrors the NextJs pages structure, creating ...

problem encountered while attempting to drag and drop list elements on a web application utilizing dhtmlx 5.0 and wijmo grid

My web application utilizes Dhtmlx 5.0, Wijmo grid, and Typescript. One feature of the app is a dialog box that displays a list of items which can be rearranged using drag and drop functionality. This feature works without any issues on Windows PCs but enc ...

How to display currency input in Angular 2

Is there a way to dynamically format input as USD currency while typing? The input should have 2 decimal places and populate from right to left. For example, if I type 54.60 it should display as $0.05 -> $0.54 -> $5.46 -> $54.60. I found this PLUN ...

Create objects in the gallery

I recently developed a React Material-UI component using Typescript: <Grid container direction="row" justifyContent="flex-start" alignItems="flex-start"> <Grid item xs={5}> <B ...

Ways to invoke the same API multiple times with various requests in Angular

I am facing a challenge in my application where I need to make multiple API calls based on an array of objects. Each object in the array should act as a payload for a separate API call when a button is clicked. If any of the API calls fail, the process sho ...

Tips on delaying the return of the Angular compiler until the subscription is complete

I'm facing an issue with a function that needs to return a value while containing a subscription. The problem I'm encountering is that the return line is being executed before the subscription ends, testFunc(){ let objectType; let modul ...

What is the best way to adjust the Material Drawer width in Reactjs to match the width of its children?

Currently, I am utilizing the Material-ui Drawer component to toggle the display of content on the right side of the screen. The functionality I am aiming for is that when the Drawer opens, it will shrink the existing content on the right without any overl ...

Custom groupBy function for arrays in TypeScript

Below is an example of an array: [ { "exam" : "1", "class": "1A1", "rooms": "245", "teachers": "A" }, { "exam" : "1", "class" ...

Tips on expanding an interface of a subclass

Using the latest versions of TypeScript and ReactJS together has presented a challenge when it comes to extending classes and their interfaces. To address this issue for several form elements that share common validation methods, I have created a BaseComp ...

The data type 'string | boolean | null' cannot be assigned to type 'boolean'. Specifically, the type 'null' cannot be assigned to type 'boolean'

Can you spot the issue in this code snippet? isAuthenticated(): boolean { var token = localStorage.getItem(ACCESS_TOKEN_KEY); return token && !this.jwtHelper.isTokenExpired(token); } Error: The variable is returning a type of 'string | bo ...

Angular2's loader is used to make Http requests

Can someone help me with displaying a loader during an HTTP request? return this.http.get(this._apiUrl) //.map(res =><Location[]> res.json()) .map(res => res.json()) .filter(x => x.length > 0) ...

The 'eventKey' argument does not match the 'string' parameter. This is because 'null' cannot be assigned to type 'string'

Encountering an issue while invoking a TypeScript function within a React Project. const handleLanguageChange = React.useCallback((eventKey: eventKey) => { setLanguage(eventKey); if(eventKey == "DE") setCurre ...

The subscription for the second Observable in RxJS concatMap is triggered individually

I am currently developing an Angular 6 application. I want the app to display a loading animation whenever there is a change in the route or if there are any pending HTTP requests. To achieve this, I have set up two Observables as follows: For httpPendingR ...

I am interested in preserving a QrCode by converting it into an image

Below is the updated code snippet: [HttpGet("GenerateQrCode")] public ActionResult<string> GenerateQrCode(string sellername, string vatregistration, string timestamp, string invoiceamount, string vatamoun) { string ltr = ((char)0x20 ...

Using AngularJS with CDN: A beginner's guide

If I need to create an app using AngularJS with Cordova in Visual Studio, do I need anything else besides the Google CDN for AngularJS? <!doctype html> <html ng-app> <head> <title>My Angular App</title> <script s ...

Identifying an SCSS file based on its class name in Angular

Currently, I'm utilizing an Angular 5 application with styles that are encapsulated within components. Upon running the ng serve command, all styles get inserted into <styles> tags within the <head> section of the page. This results in br ...

What is the rationale behind ngOnInit not being a private method in Angular?

After extensively checking both code samples and even the official documentation, I am still unable to find the information I need. Turning to Google has also yielded no results. The question that baffles me is: ngOnInit() { ... } Why do we use this syn ...

reinstate dummy of external class method in ts-jest

Problem I am encountering an issue while trying to mock a function that is imported from another class and called within the main class. Although I can successfully mock the function and return the specified values, I am unable to revert the mocked functi ...

What is the best way to invoke a function in a React component from another component?

I am working with a component structure that includes the Input component. In this component, there is a function called validate that is triggered by the onChange event. Here is a snippet of the code: https://i.sstatic.net/WjCLy.png import React, {FC, us ...