อัปเดต 2019
สิ่งนี้จะอัปเดตคำตอบด้วยFetch APIล่าสุดและไม่จำเป็นต้องใช้ jQuery
ข้อจำกัดความรับผิดชอบ: ใช้ไม่ได้กับ IE, Opera Mini และเบราว์เซอร์รุ่นเก่า ดูcaniuse caniuse
การดึงข้อมูลพื้นฐาน
มันอาจจะง่ายเหมือน:
fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
.then(response => console.log(response.text()))
ดึงข้อมูลด้วยการจัดการข้อผิดพลาด
หลังจากเพิ่มการจัดการข้อผิดพลาดอาจมีลักษณะดังนี้:
fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
.then(response => {
if (response.ok) return response;
else throw Error(`Server returned ${response.status}: ${response.statusText}`)
})
.then(response => console.log(response.text()))
.catch(err => {
alert(err);
});
รหัส PHP
นี่คือรหัสฝั่งเซิร์ฟเวอร์ใน upload.php
<?php
// gets entire POST body
$data = file_get_contents('php://input');
// write the data out to the file
$fp = fopen("path/to/file", "wb");
fwrite($fp, $data);
fclose($fp);
?>