Ajax + php Upload code without refreshing new files

Source: Internet
Author: User
Tags php file upload

If php file upload is not implemented using ajax, the effect is not very good, and the user experience is not very good. Let's take a look at this ajax + php new file upload code. Ajax + php Upload code without refreshing new files

Ajax + php tutorial without refreshing file upload code
<! Doctype html public "-// w3c // dtd xhtml 1.0 transitional // en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<Html xmlns = "http://www.bKjia. c0m/1999/xhtml">
<Head>
<Meta http-equiv = "content-type" content = "text/html; charset = gb2312"/>
<Title> ajax + php Upload code without refreshing new files </title>
</Head>
<Body>
<Style>
. Fu_list {
Width: 600px;
Background: # ebeb;
Font-size: 12px;
}
. Fu_list td {
Padding: 5px;
Line-height: 20px;
Background-color: # fff;
}
. Fu_list table {
Width: 100%;
Border: 1px solid # ebebeb;
}
. Fu_list thead td {
Background-color: # f4f4f4;
}
. Fu_list B {
Font-size: 14px;
}
/* File container style */
A. files {
Width: 90px;
Height: 30px;
Overflow: hidden;
Display: block;
Border: 1px solid # bebebe;
Background: url (img/fu_btn.gif) left top no-repeat;
Text-decoration: none;
}
A. files: hover {
Background-color: # ffffee;
Background-position: 0-30px;
}
/* Set file to transparent and overwrite the entire trigger surface */
A. files input {
Margin-left:-350px;
Font-size: 30px;
Cursor: pointer;
Filter: alpha (opacity = 0 );
Opacity: 0;
}
/* Unclick the dotted box */
A. files, a. files input {
Outline: none;/* ff */
Hide-focus: expression (this. hidefocus = true);/* ie */
}
</Style>
<Form id = "uploadform" action = "file. php">
<Table border = "0" cellspacing = "1" class = "fu_list">
<Thead>
<Tr>
<Td colspan = "2"> <B> upload a file </B> </td>
</Tr>
</Thead>
<Tbody>
<Tr>
<Td align = "right" width = "15%" style = "line-height: 35px;"> Add file: </td>
<Td> <a href = "webpage effect: void (0 ); "class =" files "id =" idfile "> </a> </td>
</Tr>
<Tr>
<Td colspan = "2"> <table border = "0" cellspacing = "0">
<Thead>
<Tr>
<Td> file path </td>
<Td width = "100"> </td>
</Tr>
</Thead>
<Tbody id = "idfilelist">
</Tbody>
</Table> </td>
</Tr>
<Tr>
<Td colspan = "2" style = "color: gray"> tip: You can upload up to <B id = "idlimit"> </B> files simultaneously, only <B id = "idext"> </B> files can be uploaded. </Td>
</Tr>
<Tr>
<Td colspan = "2" align = "center" id = "idmsg"> <input type = "button" value = "Start upload" id = "idbtnupload" disabled = "disabled "/>
& Nbsp;
<Input type = "button" value = "cancel all" id = "idbtndel" disabled = "disabled"/>
</Td>
</Tr>
</Tbody>
</Table>
</Form>
<Script type = "text/Webpage effects">

Var isie = (document. all )? True: false;

Var $ = function (id ){
Return "string" = typeof id? Document. getelementbyid (id): id;
};

Var class = {
Create: function (){
Return function (){
This. initialize. apply (this, arguments );
}
}
}

Var extend = function (destination, source ){
For (var property in source ){
Destination [property] = source [property];
}
}

Var bind = function (object, fun ){
Return function (){
Return fun. apply (object, arguments );
}
}

Var each = function (list, fun ){
For (var I = 0, len = list. length; I <len; I ++) {fun (list [I], I );}
};

// File Upload class
Var fileupload = class. create ();
Fileupload. prototype = {
// Form object, file control storage space
Initialize: function (form, folder, options ){
 
This. form = $ (form); // form
This. folder = $ (folder); // file control storage space
This. files = []; // file set
 
This. setoptions (options );
 
This. filename = this. options. filename;
This. _ framename = this. options. framename;
This. limit = this. options. limit;
This. distinct = !! This. options. distinct;
This. extin = this. options. extin;
This. extout = this. options. extout;
 
This. oninifile = this. options. oninifile;
This. onempty = this. options. onempty;
This. onnotextin = this. options. onnotextin;
This. onextout = this. options. onextout;
This. onlimite = this. options. onlimite;
This. onsame = this. options. onsame;
This. onfail = this. options. onfail;
This. onini = this. options. onini;
 
If (! This. _ framename ){
// Create different iframe for each instance
This. _ framename = "uploadframe _" + math. floor (math. random () * 1000 );
// Ie cannot modify the iframe name
Var oframe = isie? Document. createelement ("<iframe name =" "+ this. _ framename +" ">"): document. createelement ("iframe ");
// Set name for ff
Oframe. name = this. _ framename;
Oframe. style. display = "none ";
// If appendchild is not fully loaded in the ie file, an error is returned.
Document. body. insertbefore (oframe, document. body. childnodes [0]);
}
 
// Set the form attribute. The key is that the target must point to iframe.
This.form.tar get = this. _ framename;
This. form. method = "post ";
// Note that the form of ie does not have the enctype attribute. Use encoding.
This. form. encoding = "multipart/form-data ";

// Sort once
This. ini ();
},
// Set the default attribute
Setoptions: function (options ){
This. options = {// Default Value
Filename: "files []", // name of the file upload control, used in combination with the background
Framename: "", // iframe name. to customize iframe, set the name here.
Oninifile: function () {}, // execute when organizing files (where the parameter is a file object)
Onempty: function () {}, // executed when the file is null
Limit: 10, // limit on the number of files, 0 is not limited
Onlimite: function () {}, // executed when the number of files exceeds the limit
Distinct: true, // whether the same file is not allowed
Onsame: function () {}, // executed when the same file exists
Extin: ["gif", "jpg", "rar", "zip", "iso", "swf", "exe"], // suffix allowed
Onnotextin: function () {}, // executed when the suffix is not allowed
Extout: [], // disable suffix. If extin is set, extout is invalid.
Onextout: function () {}, // It is executed when the suffix is disabled
Onfail: function () {}, // executed when the file fails to pass the detection (where the parameter is a file object)
Onini: function () {}// executed during resetting
};
Extend (this. options, options || {});
},
// Organize the space
Ini: function (){
// Sort the file set
This. files = [];
// Sort the file space and put the file with values into the file set
Each (this. folder. getelementsbytagname ("input"), bind (this, function (o ){
If (o. type = "file") {o. value & this. files. push (o); this. oninifile (o );}
}))
// Insert a new file
Var file = document. createelement ("input ");
File. name = this. filename; file. type = "file"; file. onchange = bind (this, function () {this. check (file); this. ini ();});
This. folder. appendchild (file );
// Execute the additional program
This. onini ();
},
// Check the file object
Check: function (file ){
// Check Variables
Var bcheck = true;
// Check for null values, limit on the number of files, suffix names, and identical files
If (! File. value ){
Bcheck = false; this. onempty ();
} Else if (this. limit & this. files. length> = this. limit ){
Bcheck = false; this. onlimite ();
} Else if (!! This. extin. length &&! Regexp (". (" + this. extin. join ("|") + ") $", "I"). test (file. value )){
// Check whether suffix names are allowed
Bcheck = false; this. onnotextin ();
} Else if (!! This. extout. length & regexp (". ("+ this. extout. join ("|") + ") $", "I "). test (file. value )){
// Check whether suffix names are prohibited
Bcheck = false; this. onextout ();
} Else if (!! This. distinct ){
Each (this. files, function (o) {if (o. value = file. value) {bcheck = false ;}})
If (! Bcheck) {this. onsame ();}
}
// Failed Detection
! Bcheck & this. onfail (file );
},
// Delete the specified file
Delete: function (file ){
// Remove the specified file
This. folder. removechild (file); this. ini ();
},
// Delete all files
Clear: function (){
// Clear the file space
Each (this. files, bind (this, function (o) {this. folder. removechild (o) ;})); this. ini ();
}
}

Var fu = new fileupload ("uploadform", "idfile", {extin: ["gif", "jpg"],
Oninifile: function (file) {file. value? File. style. display = "none": this. folder. removechild (file );},
Onempty: function () {alert ("select a file ");},
Onlimite: function () {alert ("Upload limit exceeded ");},
Onsame: function () {alert ("the same file already exists ");},
Onnotextin: function () {alert ("only allow upload" + this. extin. join (",") + "file ");},
Onfail: function (file) {this. folder. removechild (file );},
Onini: function (){
// Display the file list
Var arrrows = [];
If (this. files. length ){
Var othis = this;
Each (this. files, function (o ){
Var a = document. createelement ("a"); a. innerhtml = "cancel"; a. href = "javascript: void (0 );";
A. onclick = function () {othis. delete (o); return false ;};
Arrrows. push ([o. value, a]);
});
} Else {arrrows. push (["<font color = 'Gray '> no file added </font>", "& nbsp;"]);}
Addlist (arrrows );
// Set button
$ ("Idbtnupload"). disabled = $ ("idbtndel"). disabled = this. files. length <= 0;
}
});

$ ("Idbtnupload"). onclick = function (){
// Display the file list
Var arrrows = [];
Each (fu. files, function (o) {arrrows. push ([o. value, "& nbsp;"]) ;});
Addlist (arrrows );
 
Fu. folder. style. display = "none ";
$ ("Idprocess"). style. display = "";
$ ("Idmsg"). innerhtml = "adding files to your online storage. Please wait ...... <Br/> a program does not respond for a long time due to network problems. Please click "<a href = '? '> <Font color = 'red'> cancel </font> </a> "upload a file again ";
 
Fu. form. submit ();
}

// Function used to add a file list
Function addlist (rows ){
// Add a list based on the array
Var filelist = $ ("idfilelist"), ofragment = document. createdocumentfragment ();
// Save the list with document fragments
Each (rows, function (cells ){
Var row = document. createelement ("tr ");
Each (cells, function (o ){
Var cell = document. createelement ("td ");
If (typeof o = "string") {cell. innerhtml = o;} else {cell. appendchild (o );}
Row. appendchild (cell );
});
Ofragment. appendchild (row );
})
// The table of ie does not support innerhtml, so the table is cleared in this way.
While (filelist. haschildnodes () {filelist. removechild (filelist. firstchild );}
Filelist. appendchild (ofragment );
}


$ ("Idlimit"). innerhtml = fu. limit;

$ ("Idext"). innerhtml = fu. extin. join (",");

$ ("Idbtndel"). onclick = function () {fu. clear ();}

// Access the Home Page functions through window. parent in the background
Function finish (msg) {alert (msg); location. href = location. href ;}

</Script>
</Body>
</Html>

File. php file

<?
$ Sort = 12;
$ F_type = strtolower ("swf, jpg, rar, zip, 7z, iso, gif"); // you can specify the file type that can be uploaded.
$ File_size_max = 200*1024*1024; // limit the maximum upload capacity of a single file
$ Overwrite = 0; // specifies whether to overwrite the same file. Values: 1 (allowed) and 0 (not allowed ).
$ F_input = "files"; // set the name of the uploaded Domain Name
Foreach ($ _ files [$ f_input] ["error"] as $ key => $ error ){
$ Up_error = "no ";
If ($ error = upload_err_ OK ){
$ F_name = $ _ files [$ f_input] ['name'] [$ key]; // obtain the name of the uploaded source file
$ Uploaddir = './www. bKjia. c0m /';
$ Uploadfile = $ uploaddir. strtolower (basename ($ f_name ));

$ Tmp_type = substr (strrchr ($ f_name, "."), 1); // get the file extension
$ Tmp_type = strtolower ($ tmp_type );
If (! Stristr ($ f_type, $ tmp_type )){
Echo "<script> alert ('Sorry, you cannot upload". $ tmp_type. "Format File,". $ f_name. "File Upload Failed! ') </Script> ";
$ Up_error = "yes ";
}

If ($ _ files [$ f_input] ['SIZE'] [$ key]> $ file_size_max ){

Echo "<script> alert ('Sorry, the file you uploaded". $ f_name. "capacity is". round ($ _ files [$ f_input]
['SIZE'] [$ key]/1024). "kb, greater than the specified". ($ file_size_max/1024). "kb, Upload Failed! ') </Script> ";
$ Up_error = "yes ";
}

If (file_exists ($ uploadfile )&&! $ Overwrite ){
Echo "<script> alert ('Sorry, File". $ f_name. "already exists. Upload Failed! ') </Script> ";
$ Up_error = "yes ";
}
$ String = 'abcdefghijklmnopgrstuvwxyz0123456789 ';
$ Rand = '';
For ($ x = 0; $ x <12; $ x ++)
$ Rand. = substr ($ string, mt_rand (0, strlen ($ string)-1), 1 );
$ T = date ("ymdhis"). substr ($ gettime [0], 2, 6). $ rand;
$ Attdir = "./file /";
If (! Is_dir ($ attdir ))
{Mkdir ($ attdir );}
$ Uploadfile = $ attdir. $ t. ".". $ tmp_type;
If ($ up_error! = "Yes") and (move_uploaded_file ($ _ files [$ f_input] ['tmp _ name']

[$ Key], $ uploadfile ))){


$ _ Msg = $ _ msg. $ f_name. 'upload successful n ';


}
Else {
$ _ Msg = $ _ msg. $ f_name. 'upload failed n ';
}
}
 
}
Echo "<script> window. parent. finish ('". $ _ msg. "'); </script> ";
/*
If php file upload is not implemented using ajax, the effect is not very good, and the user experience is not very good. Let's take a look at this ajax + php new file upload code.
*/
?>

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.