Home > Article > Web Front-end > JavaScript implements uploading files to the background for reception
In the plug-in management interface of WordPress background management, I want to add an ajax upload without refreshing. Let me talk about the idea first: To upload a file, you must obtain the data stream of the current file, and then pass The ajax post method is sent to the server for processing.
(1) How to obtain the data stream of the current file?
Answer: Append the file data in a variable through the object instantiated by FormData()
(2) How to obtain the data?
Answer: In the input form with type file, it comes with a files attribute.
HTML page sends a file upload request:
<input type="file" name="upload_img" id='upload_img'/> <img src="" id='myfile_img' alt='' title='' width='300'/> <script type="text/javascript"> var uploadImg = document.getElementById('upload_img'); var myfileImg = document.getElementById('myfile_img'); uploadImg.onchange = function() { var imgName = this.files[0].name; //let reader = new FileReader(); var fordata = new FormData(); fordata.append('my_file',this.files[0]); //向服务器发送文件数据 ajaxPost(fordata,function(obj){ var content = JSON.parse(obj.response); console.log(content); if(content.status == 'sucess'){ myfileImg.src = './images/'+imgName; } }); } function ajaxPost(data,fn) { var xhr = new XMLHttpRequest(); xhr.open('post','./upload.php','true'); xhr.send(data); xhr.onload = function() { fn(this); } } </script>
The server processes the file data and generates the uploaded file:
$success = array('status' => 'sucess', 'code' => '1'); $error = array('status' => 'error', 'code' => '0'); if (!empty($_FILES)) { $file = $_FILES['my_file']; $new_file_dir = dirname(__FILE__) . '/images/' . $file['name']; @move_uploaded_file($file['tmp_name'], $new_file_dir); exit(json_encode($success)); } else { exit(json_encode($error)); }
Related recommendations:
JavaScript Introduction to the method of uploading files without refreshing them
The above is the detailed content of JavaScript implements uploading files to the background for reception. For more information, please follow other related articles on the PHP Chinese website!