Transfer a JSON file to a server effortlessly using drag and drop, no need for AJAX

I'm having trouble with this issue (It's a straightforward Drag & Drop implementation):

<!DOCTYPE html>
<style type="text/css>
body {
font-family: "Arial",sans-serif;
}
.dropzone {
width: 300px;
height: 300px;
border: 2px dashed #ccc;
color: #ccc;
line-height: 300px;
text-align: center;
}

.dropzone.dragover {
border-color: #000;
color: #000;
}
</style>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id = "uploads"></div>
<div class="dropzone" id="dropzone">Drop Here</div>

<script type="text/javascript">
        (function () {
            var dropzone = document.getElementById('dropzone');

            dropzone.ondrop = function (e) {
                e.preventDefault();
                this.className = 'dropzone';
            };
            // On the area
            dropzone.ondragover = function () {
                this.className = 'dropzone dragover';
                return false;
            };

            // Leave the area while pressing
            dropzone.ondragleave = function () {
                this.className = 'dropzone';
            };

            dropzone.ondrop = function (event) {
                event.preventDefault();
                this.className = 'dropzone';
            };

        }());

    </script>
</body>
</html>

I'm wondering how to retrieve the file that I dropped into the "box" (a JSON file in my case). How can I access this file and perform operations on it (like sending it to a server in POST format).

I'd like to understand how to retrieve this dropped file so that I can work with it in some way.

Also, I'm interested in sending this json as an object to a server that can process the data (preferably using an asynchronous HttpPOST request). I want to accomplish this without using ajax or similar methods (not $.get, etc.). I'd like to achieve this using fetch, then and catch methods. I'm unsure of how this process works, so any assistance would be greatly appreciated.

Thank you!

Answer №1

Mozilla offers a great example on how to retrieve a dropped file

To access the dataTransfer property in the DragEvent object.

(function() {
  var dropzone = document.getElementById('dropzone');

  dropzone.ondrop = function(e) {
    e.preventDefault();
    this.className = 'dropzone';
  };

  dropzone.ondragover = function() {
    this.className = 'dropzone dragover';
    return false;
  };

  dropzone.ondragleave = function() {
    this.className = 'dropzone';
  };

  dropzone.ondrop = function(event) {
    const [item] = event.dataTransfer.items;
    
    console.log(item.getAsFile());
    
    event.preventDefault();
    this.className = 'dropzone';
  };

}());
body {
  font-family: "Arial", sans-serif;
}

.dropzone {
  width: 300px;
  height: 300px;
  border: 2px dashed #ccc;
  color: #ccc;
  line-height: 300px;
  text-align: center;
}

.dropzone.dragover {
  border-color: #000;
  color: #000;
}
<div id="uploads"></div>
<div class="dropzone" id="dropzone">Drop Here</div>

I want to understand how I can send this JSON as an object to a server that can interpret the data in an async HttpPOST request. I prefer not to use ajax or similar methods (like $.get, etc.). I would like to achieve this using fetch, this, and catch. I am seeking guidance on how to accomplish this.

This can be a bit tricky. It might be more convenient to utilize FormData as sending a Blob in this manner is simpler.

const formData = new FormData();
formData.append("file", file);

fetch(url, {method: 'POST', body: formData})

However, for application/json conversion, you can either transform the File/Blob object to dataURL or base64 with details about the file extension

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

Discrepancy in functionality between Android and JavaScript Parse API

Using the open source version of Parse Server as a back end, my Android application saves objects to the server's DB in the form of key-value pairs encoded as JSON. However, when trying to retrieve the same object from an Ionic 2 app using the JS Pars ...

Utilizing D3.js: Applying Multiple Classes with Functions

My current project involves using D3.js and I've encountered a particular challenge that has me stumped. In the CSV file I'm working with, there are columns labeled "Set" and "Year". My goal is to extract values from these columns and use them a ...

From where does the require.js file originate?

Currently, I am learning Angular 2 from the tutorial available at https://github.com/pkaul/maven-typescript-example. Once I proceed with the 3rd step (mvn jetty:run), a runnable war folder is generated in the example-webapp/target directory. However, I ha ...

Utilizing a relationship's remote method in Loopback

My current project involves using loopback where I have a MyUser model that is related (hasMany) to a SellerRequests model. After discovering that I can create a new seller request linked to the user by making a POST request to /api/MyUsers/:id/sellerRequ ...

Android app encountering Volley throwing JsonPars exception

Hey there! I am a beginner in Android development and I'm trying to get some practice with Volley. Below is a code sample that I wrote: RequestQueue rq = Volley.newRequestQueue(this); String urlStr="https://api.github.com/users/mralexgray/repos"; ...

Newtonsoft Json is capable of parsing up to 16 significant digits accurately

After analyzing the JSON provided below: { "Item1": 123456789.0123456789, "Item2": "123456789.0123456789", "Item3": 1.234567890123456789, "Item4": 1234567890123456789 } This is how I parse it: string data = "{\"Item1\":12345678 ...

Ways to retrieve the length of the parent array within a component in AngularJS

Is there a way to access the value of a property in the parent from within a component? Parent: export class Animal{ animalID ?: Array<number>; { Child: import {Component, Input} from '@angular/core'; import {Animal} from '../anim ...

An error was encountered: The object 'object object' does not have the 'on' method available

I want to experiment with this website: However, I am encountering an error without any events triggering. I am confused why the method "on" is not being found even on page load. <head> <link href="css/scrollable-horizontal.css" rel="styleshe ...

Show HTML form elements on the page using jQuery or JavaScript

Is there a jQuery or JS library that can perform the following task: If the user inputs 'x' in A01, then make A01_1 visible. Otherwise, do nothing. <form id="survey"> <fieldset> <label for="A01">A01</label&g ...

Changing the value of a JSON object

My goal is to update a value in a JSON file by removing the last character from a URL. I wrote the following code, but unfortunately, it doesn't seem to be making any changes. I'm a bit lost on what went wrong... def modify_json(file): with ...

Which framework should be used: client-side or server-side?

I am working on a project similar to craiglist, where users can post announcements for everyday items like cars and flats. I have already developed a significant portion of the backend using a RESTful API in three-tier architecture with Java, connecting to ...

Vue 3 - Compelled to utilize any data type with computedRef

Recently, I've been diving into Vue/Typescript and encountered a puzzling error. The issue revolves around a class named UploadableFile: export class UploadableFile { file: File; dimensions: Ref; price: ComputedRef<number>; ... constr ...

Updating elements within a subarray in JavaScript can easily be accomplished by accessing the

I need help updating nested array elements in JavaScript. I want to convert dates into a different format. How can I update the nested elements? array1 = [ { "week": [ "2019-05-06T16:00:00.000Z", "2019-05-07T16:00:00.000Z", "2019-05-08T16:00:00.000Z", "20 ...

Encountering an error when trying to destructure a property of null

The concept of destructuring is fascinating, but I have been facing some challenges when trying to destructure nested objects. Consider the following code snippet: const { credit: { amount }, } = userProfile This can be risky because if the &ap ...

What is the best way to configure a basic firebase ajax call?

I wanted to explore using AJAX instead of set to interact with Firebase. However, when I attempted to do so with the code below in my test.html file, I encountered an error message in the console: XMLHttpRequest cannot load . No 'Access-Control-Allow ...

Ajax ensures that the site stays active and responsive

Struggling to understand how to make this code work. var request; if(window.XMLHttpRequest){ request= new XMLHttpRequest(); }else{ request = new ActiveXObject("Microsoft.XMLHTTP"); } var handleStateChange = function () { switch (request.re ...

Directives for Nested Elements in AngularJS

I am currently working on creating two custom elements: <accordion> and <accordion-group-active>. .directive('accordion', function () { return { restrict: 'E', replace: true, transclude: true, ...

Using AJAX to pass post variables

Here is a link I have: <a class="tag" wi_id="3042" wl_id="3693" for_user_id="441" href="#a"> This link triggers an ajax call. $(".tag").click(function() { var for_user_id = $(this).attr("for_user_id"); var wl_id = $(this).attr("wl_ ...

What happens when an app crashes due to a missing object in the JSON response?

When creating a model using my response to create a model with JSON, certain parameters may or may not be present in the response. Here is an example of my code: { "result": { "success": true, "data": [ { "uid": "xxxxxxx", "total_activities": "1 ...

Toggle class to a div upon clicking menu item

Seeking assistance with jQuery to develop a video player featuring a sub menu for displaying various content options upon selection. Here is a snapshot of the frontend design: view image Upon clicking on 'video' or 'audio', a distinct ...