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

Source: Internet
Author: User

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

Two days ago, the project needed to use the asynchronous upload of images and display of the upload progress function. So I found many foreign articles and ran into various pitfalls. Here I wrote an article to record them.

HTML
 

There is nothing to say about HTML code. There is a form 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, beforeSubmit: function () {// processing before uploading an image}, uploadProgress: function (event, position, total, percentComplete) {// control the progress bar here}, success: function () {}, error: function (data) {alert ('upload image error') ;}}) ;}); // specifies a file selection event. When an image is selected, 'form' is submitted. $ (# Fileupload). on (change, function () {$ (this). parent (). submit ();});
PHP

  
Pitfalls: Serialized form, because it is a file, cannot passval(),text()To get its value, you can only submit it by serializing the form. Use in the code.serialize(), Another approach is to use.FormData()But the experiment was normal at the beginning, and an error was reported later. On stackoverflow.com, someone saw that someone encountered the same problem and did not solve it, so they gave up. CommonajaxThere is no way or it is difficult to get the upload progress. Here we use a plug-in jQuery Form Plugin, which is easy to use.ajaxConfiguration can be used, and there are a lot of practical functions and detailed use documents. Recommended ~ajaxThe three parameters for uploading images must be configured.contentType: false, cache: false, processData:false,. Obtain the local preview image. This method may cause browser compatibility problems.
$(#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]); }}
In php, although Ajax usesPOSTMethod, but all files are used in the background.$_FILES. You can use$_FILES['file']['type']To determine the file format for security processing, we will only demonstrate it here. There are other parameters, suchtmp_nameIs the file path,nameIs the file name. You can usemove_uploaded_file()To save the file to the server. I will not talk about it here. Other supplements

In addition, you can add @ _ w by setting it if you do not click New pages.formOftargetProperty pointing to a hiddeniframe. Let thatiframeRefresh the jump page. The jQuery Form in mentioned above also supports this.
We also recommend the jquery-iframe-transport plug-in.

Recommended reading uploading-files-with-ajax image-upload-example jquery-progress-bar-for-php-ajax-file-upload

javascriptI am a newbie. I hope this article will help more people who encounter the same problems. If you do not write well or are not correct, I hope your colleagues will kindly point it 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.