使用 HTML5 文件上传和 AJAX 和 jQuery
提交表单时,捕获提交过程并尝试运行以下代码段以进行文件上传 −
// 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); }
然后,在服务器端(即 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);
广告