Home > Web Front-end > JS Tutorial > jQuery Ajax file upload (php)

jQuery Ajax file upload (php)

高洛峰
Release: 2017-01-06 14:41:03
Original
1190 people have browsed it

How to implement jQuery's Ajax file upload, PHP faithful file upload.
AJAX upload file, PHP upload file.

[PHP file upload]

Before starting, I think it is necessary to briefly explain the principle of uploading files through the WEB.
Actually, whether it is PHP, JSP, or ASP that processes uploaded files here, the WEB has already uploaded the files to the server. We just use the upload processing function to process the uploaded files.
The processing functions are generally implemented using server-side languages ​​such as PHP, JSP, and ASP. So how to upload files through WEB (HTTP protocol?) You need HTML code similar to the following:
test.html

<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>
Copy after login

Note: enctype="multipart/form-data" is required , it tells the FORM table that this is a file upload type. Once the request is successful, the file will be uploaded to the temporary folder of the server.
As for how the file will be processed after reaching the destination, that is PHP , JSP, ASP.
(However, don’t be happy too early. If the file has not been moved to other places or renamed, the file will be deleted at the end of the form request. So we have to write a script to process uploaded files)
Here we use PHP to process
do_file_upload.php

<?php
$error = ""; //上传文件出错信息
$msg = "";
$fileElementName = &#39;picture&#39;;
    $allowType = array(".jpg",".gif",".png"); //允许上传的文件类型
    $num      = strrpos($_FILES[&#39;picture&#39;][&#39;name&#39;] ,&#39;.&#39;);  
$fileSuffixName    = substr($_FILES[&#39;picture&#39;][&#39;name&#39;],$num,8);//此数可变  
$fileSuffixName    = strtolower($fileSuffixName); //确定上传文件的类型

$upFilePath             = &#39;d:/&#39;; //最终存放路径
if(!empty($_FILES[$fileElementName][&#39;error&#39;]))
{
   switch($_FILES[$fileElementName][&#39;error&#39;])
   {
    case &#39;1&#39;:
     $error = &#39;传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值&#39;;
     break;
    case &#39;2&#39;:
     $error = &#39;上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值&#39;;
     break;
    case &#39;3&#39;:
     $error = &#39;文件只有部分被上传&#39;;
     break;
    case &#39;4&#39;:
     $error = &#39;没有文件被上传&#39;;
     break;
    case &#39;6&#39;:
     $error = &#39;找不到临时文件夹&#39;;
     break;
    case &#39;7&#39;:
     $error = &#39;文件写入失败&#39;;
     break;
    default:
     $error = &#39;未知错误&#39;;
   }
}elseif(empty($_FILES[&#39;fileToUpload&#39;][&#39;tmp_name&#39;]) || $_FILES[&#39;fileToUpload&#39;][&#39;tmp_name&#39;] == &#39;none&#39;)
{
   $error = &#39;没有上传文件.&#39;;
}else if(!in_array($fileSuffixName,$allowType))
{
   $error = &#39;不允许上传的文件类型&#39;; 
}else{
  );
   if($ok === FALSE){
    $error = &#39;上传失败&#39;;
   }
}
?>
Copy after login

Another note: About the $_FILES array

This array contains all uploaded file information, that is, the upload is recorded File related information.
The contents of the $_FILES array in the above example are as follows. Let's assume that the name of the file upload field is userfile as shown in the example above. The name can be whatever you want.

$_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 side, so don't take it for granted.

$_FILES['userfile']['size']
The size of the uploaded file, in bytes.

$_FILES['userfile']['tmp_name']
The temporary file name stored on the server after the file is uploaded.

$_FILES['userfile']['error']
Error code related to the file upload. This project was added in PHP version 4.2.0.

[AJAX file upload]

In fact, it is to achieve refresh-free file upload. The IFRAME file upload principle can be used.
Actually when uploading files using PHP. . . Only the $_FILES format can be used, but if we just use JS to get its ID, such as ..document.getElementById('img').value or jquery $("#img") in the form cannot be actually uploaded (but there are still many people doing this, including me at the beginning).
But the function also requires the implementation of the so-called "asynchronous upload", what should I do? ? You can only use third-party components, or write one yourself (embed an IFRAME in the web page). But if you are considering development time, you can use a third party. Here is a good jQuery Ajax file upload component, which is "ajaxfileupload.js". Its component download address is: http://www.phpletter.com/ , there is a PHP application demo inside after downloading, which is easy to understand.
Process:
(1) Code of the file on the front end: test.php

    <script type="text/javascript" src="jquery.js"></script> 
    <script type="text/javascript" src="ajaxfileupload.js"></script>
    <script type="text/javascript">
       function ajaxFileUpload()
               {
                  $.ajaxFileUpload
                     (
                       {
                            url:&#39;doajaxfileupload.php&#39;, //你处理上传文件的服务端
                            secureuri:false,
                            fileElementId:&#39;img&#39;,
                            dataType: &#39;json&#39;,
                            success: function (data)
                                  {
                                    alert(data.file_infor);
                                  }
                               }
                         )
                       return false;
                 } 
     </script>
Copy after login

The corresponding HTML is:

        <input id="img" type="file" size="45" name="img" class="input">
        <button class="button" id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button>
Copy after login

The client is completed.

(2) On the server side doajaxfileupload.php

Here, in order to easily detect whether the value is actually passed, you can save it.
            $file_infor = var_export($_FILES,true);
                file_put_contents("d:file_infor.php"       $file_infor); Here comes the familiar information:

     array(
             &#39;name&#39;=>&#39;lamp.jpg&#39;,
             &#39;type&#39;=>&#39;image/pjpeg&#39;,
             &#39;tmp_name&#39;=>&#39;c:\windows\temp\phpFA.tmp&#39;,
             &#39;error&#39;=>0,
             &#39;size&#39;=>3127
         )
Copy after login

Of course, the real processing is similar to this:

   <?php
     $upFilePath = "d:/";
     );
   if($ok === FALSE){
    echo json_encode(&#39;file_infor&#39;=>&#39;上传失败&#39;);
   }else{
    echo json_encode(&#39;file_infor&#39;=>&#39;上传成功&#39;);
   }
   ?>
Copy after login
Another note: In fact, you can embed an IFRAME in a page and then use it in the IFRAME Native POST form submission. This plug-in for JQUERY also uses this method. It’s just that it is a dynamically generated IFRAME and form

For more jQuery Ajax file upload (php) related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template