Upload images easily by dragging and dropping a URL instead of a file

My goal is to make the following scenario possible:

Picture this: two browser windows are open - one window (a) displaying a website with a drop area for picture files, and the other window (b) containing some pictures.

I aim to drag and drop a picture directly from window (b) into the drop area of window (a), where (a) will automatically download and save the picture without requiring me to first download the picture to my computer and then upload it again to (a).

I am unsure of how to approach this using JS. Any suggestions or tips on where to begin?

Answer №1

Completing this task involves multiple steps that can be executed in various ways. Here is a basic solution outline utilizing jQuery.

Prevent Default Browser Behavior

Many browsers automatically replace the current window/tab URL with the content's URL being dragged, causing page refresh. To prevent this behavior, the initial step is to intercept these events.

window.addEventListener("dragover",function(e){
  e = e || event;
  e.preventDefault();
},false);
window.addEventListener("drop",function(e){
  e = e || event;
  e.preventDefault();
},false);

Retrieve Image URL

Create an img element without a src, along with a dropzone area, and begin listening for drop events on the dropzone. When an image is dropped, extract its URL using DataTransfer. Update the src of the empty img with the retrieved URL.

$('#dropzone').on('drop', function(e) {
    var url = e.originalEvent.dataTransfer.getData('url');
    $('#result').attr("src",url);
});

Save Image

Automating image saving via Javascript poses challenges, but workarounds like FileSaver.js exist. Using FileSaver.js requires converting the img to a blob or canvas object first, as explained here.

EXAMPLE (no saving)

window.addEventListener("dragover", function(e) {
  e = e || event;
  e.preventDefault();
}, false);
window.addEventListener("drop", function(e) {
  e = e || event;
  e.preventDefault();
}, false);

$('#dropzone')
  .on('drop', function(e) {
    e.stopPropagation();
    e.preventDefault();
    var url = e.originalEvent.dataTransfer.getData('url');
    $('#result').attr("src", url);
  });
#dropzone {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  margin: 10px;
}
#result {
  margin: 10px;
  max-width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dropzone">Drop Here</div>
<img id="result" />

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

Tips for setting elevation breakpoints for Paper components in MUI

I'm currently utilizing the MUI5 framework for my Project and I must say it's been great so far. I recently created a login page where I incorporated the Paper Component. Within the Paper Component, I wanted to specify an Elevation level. This i ...

jQuery's find method returns a null value

During my Ajax POST request, I encountered an issue where I wanted to replace the current div with the one received from a successful Ajax call: var dom; var target; $.ajax({ type: "POST", url: "http://127.0.0.1/participants", data: "actio ...

Creating a seamless and interactive online platform

I am in the process of designing a website that has a sleek and dynamic layout, rather than just a static homepage. Let me explain further: Here is my current setup so you can understand what I am trying to achieve. By dynamic, I mean that when the page ...

Passing values from Vue3 child component to parent component

Hey there, I'm currently diving into the world of Vue and I'm working on a table that dynamically displays abbreviations. I've been trying to send a searchTerm from my child component to the parent component, but I'm struggling with ge ...

What is the best way to loop through an array in JavaScript, calling a prototype function recursively within itself?

I am currently working on developing a custom polyfill for the Array.flat() method. However, I have encountered some challenges when trying to call the function recursively within itself to flatten nested arrays further. It seems that when I write code wit ...

Error: Unable to find axios module

screenshot of browser developer tool - network I have embedded the script in my base.pug file script(scr='https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js') Upon loading the page and inspecting the browser developer tool > n ...

React: Despite my efforts to return a value from render, nothing was actually returned

My current project involves creating nested components to display the dataset I have. export const MyComponent = (props) => { const groupMilestoneByYear = (data) => { // Take Milestone Data array as input and group it by Year let yearGroup ...

Tips for showcasing axios data on Vue components

I'm just starting out with Vue.js and I'm struggling to grasp how it all works. I have a function that sends data to the server and receives a response using axios. However, when I try to display the response using a variable, something seems to ...

Utilize a random file import with the help of React JS, Babel, and ES6

Having trouble displaying a random image using webpack. I have a directory with various images, such as: 1.jpg, 1-cropped.jpg 2.jpg, 2-cropped.jpg I want to fetch a random image from this directory without manually adding a reference for each file. I&apo ...

Using jQuery, create a variable that combines a text string with a

I have a list with custom bullet icons that I need help modifying using JavaScript. Specifically, I am looking for a script that can identify if the icon name is followed by a number and then add an image tag with a class based on that icon number for each ...

Query to retrieve the most recent message from all users and a specific user resulting in an empty array

My goal is to retrieve all messages exchanged between User A and any other user. This is my schema structure: const MostRecentMessageSchema = new Schema({ to: { type: mongoose.Schema.Types.ObjectId, ref: "user" }, from: { type: mongoose ...

Error occurs when React-router 6 cannot render an error component

I'm facing an issue in my React app where the custom error component I created for unmatched routes is not being rendered, instead the default error page appears. Here's a snippet of how my BrowserRouter is set up: const router = createBrowserRo ...

What could be causing the lack of response from XMLHttpRequest?

I am attempting to retrieve results from a PHP file that is connected to a database. However, the variable being sent to the database is not being sent from the XMLHttpRequest. Below is the HTML code: <input type="text" id="name"/> Here is the cor ...

Tips for accomplishing multiple event triggers and event recollection (benefits that combine features of events and promises)

What I Need Seeking an event system that meets my requirements due to the asynchronous nature of my applications. Specifically, I need the events to have the ability to fire multiple times and for listeners to immediately respond if an event has already b ...

Utilizing Jquery in the Customer Portal feature within the Salesforce platform

Struggling to incorporate a Visualforce page with Jquery UI and Salesforce Customer Portal. Unfortunately, Jquery UI seems to be taking precedence over the Standard Salesforce stylesheet. Is there a way to prevent this from happening? Any assistance on t ...

Adding LocalStorage functionality to buttons in order to switch colors can be done by storing the

I've run into an issue trying to incorporate LocalStorage with the buttons that change colors as themes in JavaScript. I'm new to coding and eager to add this feature to my personal blog. $(document).ready(function () { $(".header--theme-button ...

Is there a specific method that can be implemented in Node.js to compare two strings and identify the common words or letters?

Looking for a solution: var str1="CodingIsFun"; var str2="ProgrammingRocks"; Is there any function that can provide a true value or flag in this case? ...

Determine the frequency of a specific letter in JavaScript by utilizing the indexOf method

Hey there! I'm currently working on a code to count the occurrences of a specific letter in a string using indexOf(). However, it seems like something may be off with my implementation. Can anyone point me in the right direction? Thanks! var string = ...

Generate a dynamic jqplot chart using data retrieved from a variable and JSON data

I'm struggling with loading data into a jqplot chart via variables as it only displays the first value. I am puzzled as to why this is happening. JavaScript: $(document).ready(function () { var sin = [[20, 10, 0, 10, 15, 25, 35, 50, 48, ...

Modifying HTML input value dynamically using JavaScript does not trigger the onchange event

Within my HTML code, I have an input field that is included in a form. Here is the input field snippet: <input type="text" name="group[{$sConfigurator.groupID}]" value="{$optionTopOptionID}" id="{$formSelectID}" onChange="this.form.submit();"/> A j ...