0

document.getElementById('drag_drop').ondrop = function(event)
{
    event.preventDefault();

    var form_data  = new FormData();
    var drop_files = event.dataTransfer.files;

    for(var count = 0; count < drop_files.length; count++)
        form_data.append("images[]", drop_files[count]);

    var ajax_request = new XMLHttpRequest();

    ajax_request.open("post", "upload.php");
    ajax_request.send(form_data);
}
#drag_drop{
  background-color : #f9f9f9;
  border : #ccc 4px dashed;
  line-height : 250px;
  padding : 12px;
  font-size : 24px;
  text-align : center;
}
<div id="drag_drop">Drag & Drop File Here</div>

This code allow you to upload files using the "drag and drop" function: I drop the files in the apposite div (#drag_drop) and with JS I create a POST request to the PHP file that will upload the files...

What I want to do is that as soon as the user drops the files redirect to ANOTHER html page containing the script and then send the request to the PHP file. I have no idea how not to lose the data of the files dropped inside the div during the page change (maybe inserting form_data/drop_files in a localstorage item... (?)).

NO JQUERY.

chillin
  • 45
  • 8

1 Answers1

0

I have not tested this, but when you upload a file to your browser, you can use createObjectURL() to create a local URL where your file resides.

You can save this URL in the localStorage (or similar) and read it on the other page again.

const selectedFile = document.getElementById('input').files[0];
const objectURL = window.URL.createObjectURL(selectedFile);
localStorage.setItem('UPLOADED_FILE', objectURL);

// ... change page

const retrievedUrl = localStorage.getItem('UPLOADED_FILE');
MauriceNino
  • 6,214
  • 1
  • 23
  • 60
  • There is no "files" attribute in the div: `Uncaught TypeError: can't access property 0, document.getElementById(...).files is undefined` – chillin Jan 21 '22 at 16:16
  • Are you sure you changed this code to fit your needs? Your file resides in `event.dataTransfer.files[...]`. @chillin – MauriceNino Jan 21 '22 at 16:18
  • ok fixed but after having done this how do I insert everything in the FormData to be able to then upload it? `form_data.append("images[]", retrievedUrl);` doesn't work – chillin Jan 21 '22 at 18:15
  • You need to retrieve the object from the URL again. You can read about that here: https://stackoverflow.com/questions/11876175/how-to-get-a-file-or-blob-from-an-object-url @chillin – MauriceNino Jan 24 '22 at 08:33