Uploading files using XMLHttpRequest
11,403
Try to use FormData
instead of xhr
:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
You have access to your file with this array
:
<?php var_dump($_FILES["thefile"]); ?>
See more: http://www.w3schools.com/php/php_file_upload.asp
Author by
user225269
Updated on June 08, 2022Comments
-
user225269 almost 2 years
I'm trying to use a drag and drop plugin in javascript to upload files using ajax.
<script> DnD.on('#drop-area', { 'drop': function (files, el) { el.firstChild.nodeValue = 'Drag some files here.'; var names = []; [].forEach.call(files, function (file, i) { names.push(file.name + ' (' + file.size + ' bytes)'); var xhr = new XMLHttpRequest(); xhr.open('POST','upload.php'); xhr.setRequestHeader("Content-type", "multipart/form-data"); xhr.send(file); console.log(xhr.responseText); }); document.querySelector('#dropped-files p i').firstChild.nodeValue = names.join(', '); } }); </script>
And here's upload.php:
<?php print_r($_POST); ?>
Basically I haven't written the script to upload the file yet because I'm still figuring out how can I have access to the data that I've sent through JavaScript. Can you guide me on what to do next? How do I access the file from upload.php.