Use the ajaxfileupload. js plug-in to upload files in Ajax Mode

Source: Internet
Author: User
Tags php book jquery library
[Original] use the ajaxfileupload. js plug-in to upload files in Ajax Mode
Linuxing, 17: 52,
Programming»
Javascript,
Comment (3), reference (0 ),
Reading (16636), via this site original Big | medium | small
Reference address:

Note:This address is valid only before 23:59:59 today. Both PHP and other server scripts provide the file upload function, which is easy to implement. With JavaScript, you can upload files in Ajax mode. Although jquery does not provide such a simplified function, many plug-ins can implement it. Among them, the ajaxfileupload. js provided by phpletter.com is a lightweight plug-in, and the writing method is very similar to the Global Method $. Post () provided by jquery, which is easy to use.
However, this plug-in is too simplified. In addition to providing the path for uploading files, you cannot transmit additional values to the backend server. So I modified the script and added a data object parameter.

I. Principles
I am using PHP as a server script. I will mention how to use the move_uploaded_file () method to upload files in almost every small PHP book. I will not elaborate on it here. I want to talk about the principle of using Ajax for upload.
Because the jquery library is used all the time, when you think of Ajax, the first reaction is to try the $. Post () method, use each selector to get the value in the file box, and then submit it to the backend server. Of course, it turns out that this is not feasible. (Because of this problem, I also checked a lot of information and provided a lot of ASP scripts on the Internet. I really don't know what to say ..)
Back to the topic, it is not difficult to implement Ajax upload. There are also many methods. The phpletter.com ajaxfileupload. js plug-in mentioned in this article uses IFRAME. This is also a common method for uploading without refreshing new pages when JavaScript scripts are not used. (This method is used to write logs in the bo-blog background)
While ajaxfileupload. the JS plug-in is also very simple, that is, first use the jquery selector to obtain the file path value in the file upload box, then dynamically create an IFRAME, and create a new file box in it, the post method is provided for submission to the background. Finally, return the result to the foreground.

Ii. Use
The use of the ajaxfileupload. js plug-in is simple.
The front-end HTML code is similar:

<SCRIPT type = "text/JavaScript">
$ (# Buttonuplayd). Click (function (){
$. Ajaxfileupload ({
URL: 'doajaxfileupload. php', // the server on which you process the uploaded files
Secureuri: false, // id value corresponding to the file in the page processing code
Fileelementid: 'img ',
Datatype: 'json', // return data types: Text, XML, JSON, HTML, scrui, and jsonp
Success: function (data ){
Alert (data. file_infor );
}
})
});
</SCRIPT>
<Input id = "IMG" type = "file" size = "45" name = "IMG" class = "input">
<Button class = "button" id = "buttonupload" onclick = "Return ajaxfileupload ();"> upload </button>

Background doajaxfileupload. php script:

<? PHP
$ Upfilepath = "../attachment /";
$ OK = @ move_uploaded_file ($ _ FILES ['img '] ['tmp _ name'], $ upfilepath );
If ($ OK = false ){
Echo json_encode ('file _ infor '=> 'upload failed ');
} Else {
Echo json_encode ('file _ infor '=> 'upload successful ');
}
?>

For testing, you can save the passed variable values in a way similar to the following:

$ File_info = var_export ($ _ files, true );
$ OK = file_put_contents ("../attachment/file_info.txt", $ file_info );
If ($ OK) Exit (json_encode ('file _ infor '=> 'upload successful '));
Exit (json_encode ('file _ infor '=> 'upload failed '));

※Note
Please pay attention to the mark in the HTML code file box: Reference 1. id = 'img 'is used for ajaxfileupload. the fileelementid of the js plug-in is identified by 'img '. The jquery selector uses this string to obtain the value of the text box;
2. name = 'img 'is used to read the data of the uploaded file through $ _ FILES ['img'] When the file is submitted to the background through post. If this value is not set, the $ _ FILES variable is empty;

Therefore, these two values are indispensable and cannot be confused.

3. Support for additional parameters
Sometimes, we need to process the uploaded files in the background based on certain variables. For example, update a file. In this case, you need to pass some additional parameters to the same platform. Therefore, I modified the ajaxfileupload. js plug-in:

Reference addotherrequeststoform: function (Form, data)
{
// Add extra Parameter
VaR originalelement = $ ('<input type = "hidden" name = "" value = ""> ');
For (var key in data ){
Name = key;
Value = data [Key];
VaR cloneelement = originalelement. Clone ();
Cloneelement. ATTR ({'name': name, 'value': Value });
$ (Cloneelement). appendto (form );
}
Return form;
},

Ajaxfileupload: function (s ){
// Todo introduce global settings, allowing the client to modify them for all requests, not only timeout
S = jquery. Extend ({}, jquery. ajaxsettings, S );
VaR id = new date (). gettime ()
VaR form = jquery. createuploadform (ID, S. fileelementid );
If (S. Data) form = jquery. addotherrequeststoform (Form, S. data );
VaR IO = jquery. createuploadiframe (ID, S. secureuri );

The red part is the content I added. In this way, I can pass additional parameters in the HTML section of the foreground using code similar to the following:

URL: 'doajaxfileupload. php', // the server on which you process the uploaded files
Secureuri: false, // id value corresponding to the file in the page processing code
Data: {'test': 'test', 'OK': 'OK'}, // It is transmitted as an object. You can enter the Javascript variable value in the content section.
Fileelementid: 'img ',

The background processing script is:

Array_push ($ _ files, $ _ request );
$ File_info = var_export ($ _ files, true );
$ OK = file_put_contents ("../attachment/file_info.txt", $ file_info );
If ($ OK) Exit (json_encode ('file _ infor '=> 'upload successful '));
Exit (json_encode ('file _ infor '=> 'upload failed '));

It can be seen that the principle is very simple. It is to add the additional data object content to the form under IFRAME together, pass it to the PHP script in the background, and get these values with variables such as $ _ request.
The content of the remaining file_info.txt file in the background output is as follows: reference array (
'File' =>
Array (
'Name' => 'firefox-java.txt ',
'Type' => 'text/plain ',
'Tmp _ name' => 'd: \ tools \ XAMPP \ TMP \ phped45.tmp ',
'Error' => 0,
& Apos; size & apos; = & apos; 250 & apos,
),
0 =>
Array (
'Test' => 'test ',
'OK' => 'OK ',
'Phpsessid' => 'e0000fd4fb2abca6e802a1302805a5535 ',
),
)

With this content, I believe that the subsequent PHP script processing will not be difficult, and it will not be described here.
Download DEMO code:

Download file click here to download the file

Modified ajaxfileupload. js Plugin:

Download file click here to download the file

Iv. Appendix
There are many jquery plug-ins that provide ajax to upload files. In addition to the IFRAME method, there are also flash-based uploads. This method also provides a progress bar display.
Http://www.uploadify.com/
Http://valums.com/ajax-upload/
Http://www.fyneworks.com/jquery/multiple-file-upload/

Related logs
[Switch] the failure of jquery's toggle () method in IE 8 <tr>
[Original] differences between HTML () methods in jquery in IE and Firefox
[Switch] jquery Selector
[Original] jquery introduces tags:
Jquery,
Plugins,
Upload
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.