當提交表單時,捕獲提交過程並嘗試運行以下程式碼片段來上傳檔案-
// 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);
以上是使用HTML5檔案上傳與AJAX和jQuery的詳細內容。更多資訊請關注PHP中文網其他相關文章!