Home >Backend Development >PHP Tutorial >How to upload pictures asynchronously using Ajax (html, javascript, php)_PHP tutorial

How to upload pictures asynchronously using Ajax (html, javascript, php)_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:45:53820browse

How to upload images asynchronously using Ajax (html, javascript, php)

In the first two days of the project, I needed to use the functions of asynchronously uploading pictures and displaying the upload progress, so I found a lot of foreign articles and encountered various pitfalls over the mountains and ridges. I wrote an article to record them here.

HTML



There is nothing much to say about the HTML code, just a form and input of file type. Let's look at the js part.

javascript

<code class="language-javascript" hljs="">    //绑定了`submit`事件。    
    $(&#39;#fileupload-form&#39;).on(&#39;submit&#39;,(function(e) {
        e.preventDefault();
        //序列化表单   
       var serializeData = $(this).serialize();

       // var formData = new FormData(this);
       $(this).ajaxSubmit({
            type:&#39;POST&#39;,
            url: *yoururl*,
            dataType: &#39;json&#39;, 
            data: serializeData,            
            // data: formData,

            //attention!!!   
            contentType: false,      
            cache: false,             
            processData:false,      

            beforeSubmit: function() {
                    //上传图片之前的处理   
            },
            uploadProgress: function (event, position, total, percentComplete){ 
                //在这里控制进度条   
            },
            success:function(){

            },
            error:function(data){
                alert(&#39;上传图片出错&#39;);
            }
        });
    }));

    //绑定文件选择事件,一选择了图片,就让`form`提交。   

    $(#fileupload).on(change, function() {
        $(this).parent().submit();
    });</code>

PHP

<code class="language-php" hljs=""><!--?php
    //通过$_FILES[]去获取文件
    echo '$_FILES['file']';</code--></code>

遇到的坑:

Its value can be obtained through methods such as 序列化表单,因为是文件,不能通过<code>val() and text(), which can only be submitted through a serialized form. .serialize() is used in the code. Another way is to use .FormData() to submit. However, during the experiment, it worked normally at first, but later an error was reported. On stackoverflow.com, someone saw that someone had encountered the same problem and had no solution, so they gave up. For ordinary ajax, it is impossible or difficult to get the upload progress. A plug-in, jQuery Form Plugin, is used here. The method of use is very simple. The original configuration of ajax can be used, and it has many practical functions and detailed usage documents. Recommended ~ ajaxThese three parameters for uploading images must be configured contentType: false, cache: false, processData:false,. Get a local preview, this method may have browser compatibility issues.
<code class="language-php" hljs=""><code class="language-javascript" hljs="">$(#fileupload).change(function(){
    if (this.files && this.files[0]) {
       var reader = new FileReader();            
       reader.onload = function (e) {
            $(&#39;#theImg&#39;).attr(&#39;src&#39;, e.target.result);
        }
       reader.readAsDataURL(this.files[0]);
   }
}</code></code>
Note in the php part that although Ajax uses the <code>POST<code class="language-php" hljs="">php部分注意虽然Ajax那里使用的是<code>POST method, when accepting files in the background, $_FILES<code>$_FILES. You can use $_FILES['file']['type']<code>$_FILES['file']['type'] to determine the file format for safe processing. We are just demonstrating here. There are other parameters, such as tmp_name<code>tmp_name is the file path, and name<code>name is the file name. After receiving in the background, you can use move_uploaded_file()<code>move_uploaded_file() to save the file to the server. Not much to say here.

Other supplements<code class="language-php" hljs="">其他补充

In addition, @_w student added that you can also point to a current page by setting the <code>target<code class="language-php" hljs="">另外@_w同学补充,不刷新页面还可以通过设置<code>form attribute of form<code>target without refreshing the page. Hidden iframe<code>iframe to achieve. Let that iframe<code>iframe refresh the jump page. The jQuery Form Plugin mentioned above also allows you to do this.
In addition, I recommend a plug-in jquery-iframe-transport

Recommended reading<code class="language-php" hljs="">推荐阅读

uploading-files-with-ajax image-upload-example jquery-progress-bar-for-php-ajax-file-upload <code class="language-php" hljs="">uploading-files-with-ajax image-upload-example jquery-progress-bar-for-php-ajax-file-upload

<code>javascript<code class="language-php" hljs=""><code>javascript I am a newbie, I hope this article can help more people who encounter the same problem. If something is written poorly or incorrectly, I hope colleagues can kindly point it out.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1036925.htmlTechArticleHow to use Ajax to upload images asynchronously (html, javascript, php) Asynchronous uploading was needed in the project in the first two days Pictures and the function of showing the upload progress, so I found a lot of foreign articles and went over the mountains...
Statement:
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