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. Commonajax
There 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.ajax
Configuration can be used, and there are a lot of practical functions and detailed use documents. Recommended ~ajax
The 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 usesPOST
Method, 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_name
Is the file path,name
Is 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.form
Oftarget
Property pointing to a hiddeniframe
. Let thatiframe
Refresh 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
javascript
I 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.