使用HTML5文件上传与AJAX和jQuery
当提交表单时,捕获提交过程并尝试运行以下代码片段来上传文件 -
// File 1var 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);