JQuery Ajax File Upload (php)

Source: Internet
Author: User
Tags php file upload

How to Implement jQuery's Ajax file upload and PHP's truthful file upload.
Upload files using AJAX and files using PHP.

PHP File Upload]

Before I start, I think it is necessary to briefly describe the principle of uploading files through the WEB.
In fact, whether it is PHP, JSP, or ASP to process uploaded files, the WEB has already uploaded the files to the server. We just use the upload processing function to process uploaded files.
Processing functions are generally implemented in PHP, JSP, ASP, and other server languages. So how to upload files through the WEB (HTTP protocol ?) You need the following HTML code:
Test.html

Copy codeThe Code is as follows:
<Form action = "do_file_upload.php" method = "post" enctype = "multipart/form-data">
<P> Pictures:
<Input type = "file" name = "picture"/>
<Input type = "submit" value = "Send"/>
</P>
</Form>

Note: enctype = "multipart/form-data" is required and tells the FORM table that this is a file upload type. Once this request is successful, the file is uploaded to the temporary folder on the server,
What will happen to the file after it reaches its destination? PHP, JSP, and ASP.
(However, you should not be happy too early. If the file is not moved to another place or renamed, the file will be deleted at the end of the form request. So we need to write a script to process uploaded files)
Here we use PHP for processing
Do_file_upload.php

Copy codeThe Code is as follows:
<? Php
$ Error = ""; // File Upload error message
$ Msg = "";
$ FileElementName = 'picture ';
$ AllowType = array (". jpg", ". gif", ". png"); // specifies the file type that can be uploaded.
$ Num = strrpos ($ _ FILES ['picture '] ['name'],'. ');
$ FileSuffixName = substr ($ _ FILES ['picture '] ['name'], $ num, 8); // variable value
$ FileSuffixName = strtolower ($ fileSuffixName); // you can specify the object type.

$ UpFilePath = 'd:/'; // The final storage path.

If (! Empty ($ _ FILES [$ fileElementName] ['error'])
{
Switch ($ _ FILES [$ fileElementName] ['error'])
{

Case '1 ':
$ Error = 'the uploaded file exceeds the limit of the upload_max_filesize option in php. ini ';
Break;
Case '2 ':
$ Error = 'the size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form ';
Break;
Case '3 ':
$ Error = 'only part of the file is upload ';
Break;
Case '4 ':
$ Error = 'no file is upload ';
Break;

Case '6 ':
$ Error = 'temporary folder not found ';
Break;
Case '7 ':
$ Error = 'file write failed ';
Break;
Default:
$ Error = 'unknown error ';
}
} Elseif (empty ($ _ FILES ['filetoupload'] ['tmp _ name']) | $ _ FILES ['filetoupload'] ['tmp _ name'] = 'None ')
{
$ Error = 'file not uploaded .';
} Else if (! In_array ($ fileSuffixName, $ allowType ))
{
$ Error = 'file type not allowed to be uploaded ';
} Else {
);
If ($ OK = FALSE ){
$ Error = 'upload failed ';
}
}
?>

Note: about the $ _ FILES Array

This array contains information about all uploaded files, that is, information about uploaded files.
In the preceding example, the content of the $ _ FILES array is as follows. Assume that the name of the file upload field is userfile, as shown in the preceding example. The name can be named at will.

$ _ FILES ['userfile'] ['name']
The original name of the client machine file.

$ _ FILES ['userfile'] ['type']
The MIME type of the file, if the browser provides this information. An example is "image/gif ". However, this MIME type is not checked on the PHP end, so do not take it for granted.

$ _ FILES ['userfile'] ['SIZE']
Size of the uploaded file, in bytes.

$ _ FILES ['userfile'] ['tmp _ name']
Temporary File Name stored on the server after the file is uploaded.

$ _ FILES ['userfile'] ['error']
The Error Code related to the file upload. This project was added in PHP 4.2.0.

[AJAX File Upload]

In fact, it is to implement the upload of non-Refresh files. The IFRAME File Upload principle can be used.
In fact, when using PHP to upload files... You can only use $ _ FILES, but if we only use JS to retrieve its ID, such as <input id = 'img 'type = 'file'> .doc ument. getElementById ('img '). $ ("# img") in the form of value or jquery cannot be uploaded in real time (but many people still do this, and I did it at the beginning ).
However, what should I do if I need to implement the so-called "Asynchronous upload" function ?? You can only use third-party components or write one by yourself (embed an IFRAME In the webpage ). However, if you are considering the development time, use a third party. Here, there is a good jQuery Ajax File Upload Component, which is "ajaxfileupload. js" whose component is: callback.
Process:
(1) Code of the front-end file: test. php
Copy codeThe Code is as follows:
<Script type = "text/javascript" src = "jquery. js"> </script>
<Script type = "text/javascript" src = "ajaxfileupload. js"> </script>
<Script type = "text/javascript">
Function ajaxFileUpload ()
{
$. AjaxFileUpload
(
{
Url: 'doajaxfileupload. php', // the server on which you process the uploaded files
Secureuri: false,
FileElementId: 'img ',
DataType: 'json ',
Success: function (data)
{
Alert (data. file_infor );
}
}
)

Return false;
}
</Script>

The corresponding HTML is:

Copy codeThe Code is as follows:
<Input id = "img" type = "file" size = "45" name = "img" class = "input">
<Button class = "button" id = "buttonUpload" onclick = "return ajaxFileUpload ();"> Upload </button>

This completes the client.

(2) doajaxfileupload. php on the server side

Here, you can save it to check whether the value is actually passed.
$ File_infor = var_export ($ _ FILES, true );
File_put_contents ("d: file_infor.php". $ file_infor );
In this way, when you call the generated file_infor.php file, you will see the familiar information:
Copy codeThe Code is as follows:
Array (
'Name' => 'lamp.jpg ',
'Type' => 'image/pjpeg ',
'Tmp _ name' => 'C: \ windows \ temp \ phpFA. tmp ',
'Error' => 0,
'SIZE' => 3127
)


Of course, the real processing is like this:

Copy codeThe Code is as follows:
<? Php
$ UpFilePath = "d :/";
);
If ($ OK = FALSE ){
Echo json_encode ('file _ infor '=> 'upload failed ');
} Else {
Echo json_encode ('file _ infor '=> 'upload successful ');
}
?>


Another note: in fact, you can embed an IFRAME in a page, and then use the native POST form submission. JQUERY plug-in IFRAME also uses this method. However, it is a dynamically generated IFRAME and form.

Original article: http://fc-lamp.blog.163.com/blog/static/1745666872009519310153/

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.