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

Source: Internet
Author: User

The first two days of the project need to use asynchronous upload pictures and display upload progress function, so find a lot of foreign articles, over the mountains to meet all kinds of pits, here to write an article recorded.

Html

  
  

There is nothing to say about the HTML code, a form forms, and file type input. Let's look at the JS section.

Javascript

    Bind the ' Submit ' event.
        $ (' #fileupload-form '). On (' Submit ', (function (e) {e.preventdefault ();

       Serialized form var Serializedata = $ (this). Serialize ();
       var formData = new FormData (this);  $ (this). Ajaxsubmit ({type: ' POST ', url: *yoururl*, DataType: ' JSON ', data:   
            Serializedata,//Data:formdata,//attention!!! Contenttype:false, Cache:false, Processdata:false, befores Ubmit:function () {//Upload image before processing}, Uploadprogress:function (event, Positio
            N, total, percentcomplete) {//Here Control progress bar}, Success:function () {},
            Error:function (data) {alert (' Upload image error ');
    }
        });

    }));   

    Binding file Selection event, a Select the picture, let ' form ' submit.
$ (#fileupload). On (change, function () {        $ (this). Parent (). submit (); });

Php


   
    

遇到的坑: 序列化表单,因为是文件,不能通过val()text()等方法获取到它的值,只能通过序列化表单提交。代码里面使用.serialize(),有另外一种做法是使用.FormData()来提交,但是实验过程中,一开始正常,后来报错了。在stackoverflow.com上有人看到有人遇到同样地问题,没有解决,于是就放弃了。 普通的ajax是没办法或者说很难拿到上传进度的。这里使用了一个插件jQuery Form Plugin,使用方法很简单,原本ajax的配置都能用,而且有很多实用功能和详尽的使用文档。推荐~ ajax上传图片这三个参数必须配置contentType: false, cache: false, processData:false,。 获取本地预览图,这种方法可能会有浏览器兼容性问题。

$(#fileupload).change(function(){ if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#theImg').attr('src', e.target.result); } reader.readAsDataURL(this.files[0]); } }
php部分注意虽然Ajax那里使用的是POST方法,但是后台接受的时候只要是文件都是用$_FILES。你可以通过$_FILES['file']['type']去判断文件格式来做安全处理,我们这里只是演示。还有其他参数,比如tmp_name是文件路径,name是文件名。后台接收以后,你可以使用move_uploaded_file()来将文件保存到服务器上。这里就不多说。

其他补充

另外@_w同学补充,不刷新页面还可以通过设置formtarget属性指向一个当前页面隐藏的iframe来实现。让那个iframe去刷新跳转页面。上面提到的jQuery Form Plugin也支持你这么做。
另外再推荐一个插件jquery-iframe-transport

recommended reading hljs= Uploading-files-with-ajax image-upload-example jquery-progress-bar-for-php-ajax-file-upload

JavaScript , and hopefully this article will help more people with the same problems. If the writing is not good or wrong, I also hope that colleagues can kindly point out.

 



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.