未加星标

Ajax File Upload using jQuery and PHP

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

In our earlier tutorial, different methods have provided toupload file inphp. Today we’ll build a simple Ajax file upload script with jQuery and PHP . You will find many jQuery plugins for upload files or images without page refresh. But if you want to learn the Ajax file upload process and make your own Ajax file upload script, this tutorial will help you a lot.

Here we’ll show how you can upload file to the server without page refresh using jQuery, Ajax, and PHP. Using our simple Ajax file upload script , you can easily implement file upload functionality without using any 3rd party plugin.

HTML Code

The following HTML will display a file upload box. The user can select a file to upload by click on this box.

<form>
<div id="dropBox">
<p>Select file to upload</p>
</div>
<input type="file" name="fileInput" id="fileInput" />
</form> CSS Code

To make file upload box look good, the following CSS is used.

#dropBox{
border: 3px dashed #0087F7;
border-radius: 5px;
background: #F3F4F5;
cursor: pointer;
}
#dropBox{
min-height: 150px;
padding: 54px 54px;
box-sizing: border-box;
}
#dropBox p{
text-align: center;
margin: 2em 0;
font-size: 16px;
font-weight: bold;
}
#fileInput{
display: none;
} javascript Code

The jQuery is used in Ajax file upload script, so, the jQuery library needs to be loaded first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

The following JavaScript code handles the file upload process and shows the upload status to the user. Also, the below script restrict the user to upload the only image file within 1 MB. Modify the file upload restrictions based on your requirement.

$(function(){
//file input field trigger when the drop box is clicked
$("#dropBox").click(function(){
$("#fileInput").click();
});
//prevent browsers from opening the file when its dragged and dropped
$(document).on('drop dragover', function (e) {
e.preventDefault();
});
//call a function to handle file upload on select file
$('input[type=file]').on('change', fileUpload);
});
function fileUpload(event){
//notify user about the file upload status
$("#dropBox").html(event.target.value+" uploading...");
//get selected file
files = event.target.files;
//form data check the above bullet for what it is
var data = new FormData();
//file data is presented as an array
for (var i = 0; i < files.length; i++) {
var file = files[i];
if(!file.type.match('image.*')) { //check file type$("#dropBox").html("Please choose an images file.");
}else if(file.size > 1048576){//check file size (in bytes)$("#dropBox").html("Sorry, your file is too large (>1 MB)");
}else{//append the uploadable file to FormData objectdata.append('file', file, file.name);//create a new XMLHttpRequestvar xhr = new XMLHttpRequest(); //post file data for uploadxhr.open('POST', 'upload.php', true); xhr.send(data);xhr.onload = function () { //get response and show the uploading status var response = JSON.parse(xhr.responseText); if(xhr.status === 200 && response.status == 'ok'){ $("#dropBox").html("File has been uploaded successfully. Click to upload another."); }else if(response.status == 'type_err'){ $("#dropBox").html("Please choose an images file. Click to upload another."); }else{ $("#dropBox").html("Some problem occured, please try again."); }};
}
}
}

Once the user selects a file, the file data is submitted to the upload.php file for uploading using PHP.

Upload File to the Server (upload.php)

Before uploading the submitted file is validated whether the file type is allowed. After successful validation file is uploaded to the server and the response data is returned as JSON format.

<?php if(isset($_POST) == true){ //generate unique file name $fileName = time().'_'.basename($_FILES["file"]["name"]); //file upload path $targetDir = "uploads/"; $targetFilePath = $targetDir . $fileName; //allow certain file formats $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); $allowTypes = array('jpg','png','jpeg','gif'); if(in_array($fileType, $allowTypes)){ //upload file to server if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ //insert file data into the database if needed //........ $response['status'] = 'ok'; }else{ $response['status'] = 'err'; } }else{ $response['status'] = 'type_err'; } //render response data in JSON format echo json_encode($response); } Conclusion

We’ve tried to show the Ajax file upload process as simple as possible. You can extend our script with advanced functionality, like image preview, progress bar, etc. However, you can go through the following tutorials for different methods of file upload in PHP.

Drag and drop file upload using DropzoneJS and PHP Upload file using JavaScript and PHP Upload multiple images using jQuery, Ajax and PHP

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: PHPAjaxjQueryJavaJavaScriptXMLCSSHTML
分页:12
转载请注明
本文标题:Ajax File Upload using jQuery and PHP
本站链接:http://www.codesec.net/view/531340.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(32)