File Upload with ajax+php

Source: Internet
Author: User
Tags button type
In theory, this kind of file/image upload plugin has a lot of, but in the process of use will encounter a variety of problems, compatibility issues, background problems ~ ~ And so on, so since other people's wheels I use not good, then build one yourself.

This article uses Jq.ajax and PHP to implement the upload function, the front-end code is generally not bad, and some small partners in the background is not PHP, please refer to your language documents to operate.

Look first, the entire upload interface is probably this: View demo

Overall idea:

1. Create input settings type=file,id=file, style settings Opacity:0,position:absolute

2. Create a mask layer and set position:absolute and Z-index greater than file

3, create Formdata object, put file into Formdata as data

4, create Ajax, send formdata data to upload.php, listen to Ajax progress events, real-time return to upload progress

5, the response of the HTML page output server

6, upload completed, click the "continue to upload" button, open the File selection box, you can continue to upload.

HTML section, relatively simple:


<p class= "Upload" > <p class= "Uploadbox" >    <span class= "Inputcover" > select File </span><form Enctype= "" >    <input type= "file" name= "file" id= "file"/>    <button type= "button" class= "Submit" > Upload </button></form><button type= "button" class= "Upagain" > Continue uploading </button><span class= " Processbar "></span><span class=" Processnum "> No files selected </span>    </p></p>

CSS, style can be freely adjusted according to personal preferences, here is for reference only:

*{font-family: ' Microsoft Yahei '; Color: #4A4A4A;}.    upload{width:700px;    padding:20px;    border:1px dashed #ccc;    margin:100px Auto; border-radius:5px;}.    uploadbox{width:100%;    height:35px; Position:relative;}.    Uploadbox input{width:200px;    height:30px;    background:red;    Position:absolute;    top:2px;    left:0;    z-index:201;    opacity:0; Cursor:pointer;}.    Uploadbox. inputcover{width:200px;    height:30px;    Position:absolute;    top:2px;    left:0;    z-index:200;    Text-align:center;    line-height:30px;    font-size:14px;    border:1px solid #009393;    border-radius:5px; Cursor:pointer;}.    Uploadbox button.submit{width:100px;    height:30px;    Position:absolute;    left:230px;    top:2px;    border-radius:5px;    border:1px solid #ccc;    Background: #F0F0F0;    Outline:none; Cursor:pointer;}. Uploadbox button.submit:hover{background: #E0E0E0;}. Uploadbox button.upagain{width:100px;   height:30px;    Position:absolute;    left:340px;    top:2px;    Display:none;    border-radius:5px;    border:1px solid #ccc;    Background: #F0F0F0;    Outline:none; Cursor:pointer;}. Uploadbox button.upagain:hover{background: #E0E0E0;}.    processbar{Display:inline-block;    width:0;    height:7px;    Position:absolute;    left:500px;    top:14px; Background: #009393;}.    processnum{Position:absolute;    left:620px;    Color: #009393;    font-size:12px; line-height:35px;}

js section, Jq.ajax:

$ (document). Ready (function () {var inputcover = $ (". Inputcover");    var processnum = $ (". Processnum");    var Processbar = $ (". Processbar");        Upload Preparation Information $ ("#file"). Change (function () {var file = document.getElementById (' file ');        var fileName = File.files[0].name;var fileSize = file.files[0].size;         Processbar.css ("width", 0);    Verify that the file to be uploaded if (fileSize > 1024*2*1024) {inputcover.html ("<font> file is too large, please re-select </font>");    processnum.html (' no file selected ');    document.getElementById (' file '). Value = '; return false;}    else{inputcover.html (filename+ '/' +parseint (filesize/1024) + ' K ');    processnum.html (' Wait for Upload ');} })//submit Validation $ (". Submit"). Click (function () {if ("#file"). val () = = ') {alert (' Please select the file first! ');}    else{upload ();} })//Create Ajax object, send upload request function upload () {var file = document.getElementById (' file '). Files[0];var form = new Fo Rmdata (); Form.append (' myfile ', file); $.ajax ({url: ' upload.php ',//upload address async:true,//async TypE: ' Post ',//post mode data:form,//formdata data processdata:false,//do not process traffic!important contenttype:false,//do not set HTTP header                !important xhr:function () {//get upload progress myxhr = $.AJAXSETTINGS.XHR ();                    if (myxhr.upload) {MyXhr.upload.addEventListener (' progress ', function (e) {//Listen Progress Event var loaded = e.loaded;//has been uploaded var total = e.total;//Overall size var percent = Math.f Loor (100*loaded/total);//Percentage processnum.text (percent+ "%");//Digital Progress Processbar.                CSS ("width", percent+ "px");//Graph Progress}, FALSE);            } return MYXHR; }, Success:function (data) {///upload Successful callback Console.log ("Document Current location is:" +data);//Get file link Document.cookie = "url=" +data;//this line can ignore $ (". S Ubmit "). Text (' upload successful ');             $ (". Upagain"). CSS ("Display", "block");        }})}//Continue uploading $ (". Upagain"). Click (function () {$ ("#file"). Click ();p rocessnum.html (' No file selected '); ProCessbar.css ("width", 0);    $ (". Submit"). Text (' upload ');d ocument.getelementbyid (' file '). Value = '; $ (this). CSS ("display", "none"); })})

Upload finished, upload.php processing files (for server security, only paste code snippets):

<?php  if (isset ($_files["myfile"])) {      move_uploaded_file ($_files["myfile" ["Tmp_name"], "ajax/". $_ files["MyFile" ["name"]);    echo "http://www.xuxiangbo.com/ajax/". $_files["MyFile" ["Name"];} else{    echo ' no file ';}? >

Transfer from blog

Author: imin

Links: http://blog.xuxiangbo.com/im-22.html

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

PHP+sftp Implementation of file upload and download

Four methods of generating string of random characters in PHP

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.