รายละเอียด:
ใช้ในการเลือกไฟล์ ภาพ และแสดงตัวอย่างภาพที่เลือก โดยใช้เทคนิคของ JQeury+Ajax ซึ่งจะไม่ Reload ทั้งหน้า เมื่อกดปุ่ม Upload Image จะถูกส่งไปให้ Sever Script ทำงานและส่งผลลัพธ์กลับมาแสดงยังหน้าเว็บแทน
สามารถปรับแก้ให้เลือกประเภทไฟล์ เช็ค Image Type ประเภท (jpg,jpeg,or png) หรือประเภทอื่นๆ และ Upload File Size ไม่เกิน 100 Kb.
ขั้นตอนคร่าวๆในการ Code ครับ
- Include jQuery library.
- HTML page with upload field.
- jQuery Ajax code.
- PHP script to store image.
ส่วนการอธิบาย Code
Ajax Code :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$.ajax({ url: "ajax_php_file.php", // Url to which the request is send type: "POST", // Type of request to be send, called as method data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values) contentType: false, // The content type used when sending data to the server. cache: false, // To unable request pages to be cached processData:false, // To send DOMDocument or non processed data file it is set to false success: function(data) // A function to be called if request succeeds { $('#loading').hide(); $("#message").html(data); } }); |
PHP code ในการบันทึกภาพ:
1 2 3 |
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable $targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file |
อ้างอิง https://www.formget.com/ajax-image-upload-php/