Simply drag and drop the image from your browser window into the file input

Is there a way to drag an image from a browser window into a file input that I developed?

Looking for assistance in creating an event that allows me to get the image when dragging it to an input.

While I have successfully created an event to obtain the image using ctrl-v, I am wondering if it's possible to achieve the same through Drag & Drop from a browser window.

Thank you for any help!

Check out the demo here

   <div class="drop">
    <div class="cont">
        <div class="desc">
            drop / paste here your images
        </div>
    </div>
    <div class="abc">
        <img class="img-responsive drag" style="border-radius: 8px;">
    </div>
        <input type="file" id="files" multiple (change)="detectFiles($event)" accept="image/*">
   </div>

Answer №1

After reviewing your demo, I noticed that you already have the @HostListener("paste", ["$event"]) onPaste() method.

Additionally, you can include the following code:

 @HostListener("dragover", ["$event"]) public onDragOver(evt: DragEvent) {
evt.preventDefault();
evt.stopPropagation();
this.background = "#999"; }

@HostListener("dragleave", ["$event"]) public onDragLeave(evt: DragEvent) {
evt.preventDefault();
evt.stopPropagation();
this.background = "#eee"; }

@HostListener('drop', ['$event']) public onDrop(evt: DragEvent) {
evt.preventDefault();
evt.stopPropagation();
this.background = '#eee';

let files: FileHandle[] = [];
for (let i = 0; i < evt.dataTransfer.files.length; i++) {
  const file = evt.dataTransfer.files[i];
  const url = this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(file));
  files.push({ file, url });
}
if (files.length > 0) {
  this.files.emit(files);
}  }

Don't forget to add an appDrag (files)="filesDropped($event)" in your html file.

https://i.sstatic.net/Jbkuz.png

Answer №2

Ensure that your input includes an ondrop event, similar to the example below:

<input type="file" id="files" multiple (change)="detectFiles($event)" accept="image/*" ondrop="your_function_here()" />

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

Vue 3 has a known issue where scoped styles do not get applied correctly within the content of a <slot> element

Utilizing the Oruga and Storybook libraries for creating Vue 3 components. The code in the Vue file looks like this: <template> <o-radio v-bind="$props" v-model="model"> <slot /> </o-radio> </template ...

Making a Jquery Ajax Request in Real Time

Is there a way to make sure that the "Test Data" text is only displayed in the console after the book details are fully loaded into vm.books? I am trying to make a synchronous ajax call for this purpose. The code below is not producing the expected result ...

Guidelines for setting up a universal Handler using React and AXIOS

In my current project, I am utilizing ReactJs and AXIOS. My goal is to implement a global error handler without having to add a catch statement to each request throughout the codebase. To achieve this, I have created a service that consolidates all request ...

"Interactive" - Utilizing javascript and html5 to create engaging game animations

Imagine I have a base class that looks like this: function Tile(obj) { //lots of default variables such as colors and opacity here } Tile.prototype.Draw = function () { ctx.fillStyle = "rgba(" + this.Red + "," + this.Green + "," + this.Blue + "," ...

How to trigger a function in a different component using Angular 4

I have a query bar located within the header element, designed to search through a list in a separate component. How can I set up communication for the headerComponent to invoke a function in the BooksComponent? export class HeaderComponent { search ...

Unable to retrieve environment values for Angular application in AKS

Our Angular application utilizes i18n and we are in the process of deploying it on Kubernetes. To ensure that we can build once and deploy to multiple environments, I referenced this resource for configuration guidance. I have set up env.js and env.templ ...

JavaScript: Repeated Depth First Exploration for hierarchical rearrangement implemented with d3's recursion()

I'm attempting to perform a depth-first search on a complex JSON object, such as the one available through this link. My goal is to generate a modified object structure that looks like this: [ { name: "Original Object", children : [ ...

The Echart bar graph is not displaying when trying to use JSON data

Seeking assistance as a beginner in building Basic Bar inverted axes using json data. I am trying to achieve a chart similar to Bar Inverted Axes, but encountering issues with the chart not displaying properly. Utilizing Angular to develop the web applicat ...

Having trouble bringing in components to my pages in ReactJS

There seems to be an issue preventing me from importing the components onto the page, resulting in this error: ERROR in ./src/pages/Home.jsx 4:0-37 Module not found: Error: Can't resolve './components/Card' in '/home/c4p1/blog/src/pages ...

Rails Navigation Issue: JQuery Confirmation Not Functioning Properly

Having a Rails app, I wanted to replicate the onunload effect to prompt before leaving changes. During my search, I came across Are You Sure?. After implementing it on a form, I noticed that it only works on page refreshes and not on links that take you a ...

What is a more effective method for linking values with variables in an object?

Can you suggest a more efficient way to write this in JavaScript? let foo; if(bar) { foo = bar.value; } I am attempting to prevent a react error from occurring when `bar` is null if I were to use const foo = bar.value. ...

Troubleshooting issue with file upload feature in Angular for Internet Explorer 9

I have implemented a file upload method using the following code: <input type="file" name="upload-file" ng-model= "excelFile" accept=".xlsx" onchange="angular.element(this).scope().fileChanged(this);" ...

Event to discard currently selected pushpin in Bing Maps v8

There are two event styles available for a pushpin in Bing. enableHoverStyle : Boolean enableClickedStyle : Boolean To see these events/styles in action, visit the link below: My goal is to deselect an already selected pin when another pin is selected. ...

The keyboard automatically disappeared upon clicking the select2 input

Whenever I select the select2 input, the keyboard automatically closes $('select').on('select2:open', function(e) { $('.select2-search input').prop('focus',false); }); Feel free to watch this video for more i ...

Unable to redirect Firebase Hosting root to a Cloud Function successfully

Currently I am utilizing Firebase Hosting along with a Firebase.json file that is configured to direct all traffic towards a cloud function (prerender) responsible for populating meta and og tags for SEO purposes. { "hosting": { "public": "dist/pr ...

Having trouble with [at-loader] while incorporating Typescript and react-bootstrap in webpack?

While working with webpack, I encountered an error message when using a component in react-bootstrap along with typescript. The error displayed is as follows: ERROR in [at-loader] ./node_modules/react-bootstrap/esm/NavbarCollapse.d.ts:4:18 TS2320: ...

Getting data from a response in Express.js involves using the built-in methods provided by

I am a beginner at Node.js and I'm currently experimenting with client-server communication. Below are the codes I've been working on: server: app.post('/zsa', (req, res) => { res.send("zsamo"); }); client: fetch(&qu ...

javascript - Convert a string into a JSON object

Looking for assistance here as I am fairly new to this. My goal is to transform the fullName string returned from a webapp UI using Selenium WebDriverIO. Here's what I have: const fullName = "Mr Jason Biggs"; The desired outcome should be structured ...

Cypress encountered an error: Module '../../webpack.config.js' could not be located

Every time I attempt to run cypress, an error pops up once the window launches stating "Error: Cannot find module '../../webpack.config.js'" Within my plugins>index.js file, I have the following in module.exports webpackOptions: require(&apos ...

Leverage JSON data within an AngularJS controller

I have a JSON list in Angular that looks like this: vm.allnews = actualNews; After checking it with console.log, I can see that it's working fine and I am able to retrieve all news from the array list. Each news item has a title which I can display ...