Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

HTML5 File Uploads with AJAX and jQuery



When the form is submitted, catch the submission process and try to run the following code snippet for file upload −

// File 1
var myFile = document.getElementById('fileBox').files[0];
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = myFunc;

function myFunc(event) {
   var res = event.target.result; var fileName = document.getElementById('fileBox').files[0].name;
   $.post('/myscript.php', { data: res, name: fileName }, continueSubmission);
}

Then, on the server side (i.e. myscript.php) −

$data = $_POST['data'];
$fileName = $_POST['name'];
$myServerFile = time().$fileName;

// Prevent overwriting
$fp = fopen('/uploads/'.$myServerFile,'w');
fwrite($fp, $data);
fclose($fp);
$retData = array( "myServerFile" => $myServerFile );
echo json_encode($retData);
Updated on: 2020-03-04T04:58:53+05:30

602 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements