JQuery Ajax Way to upload files with two objects
First object: FormData
Second object: XMLHttpRequest
The current version of Firefox and Chrome and other support HTML5 browser perfect support for these two objects, but IE9 has not yet supported FormData objects, still using IE6? Only to the deep sigh ....
With these two objects, we can actually upload files in Ajax way.
Sample code:
Very concise code, you can achieve Ajax way to upload files, the above code using <input type= "file"/> This traditional method of selecting files to generate file objects, HTML5 also support the use of a variety of more flexible ways, such as dragging files to the specified elements generated.
Ajax has successfully uploaded the file, but then we will think of a problem, how to show the progress bar? With this problem, the mind will think, Flash? Browser plugin?
No, I don't need these things now.
Start by making a progress bar, and the progress bar is simple, using HTML5 tags:
<progress id= "ProgressBar" value= "0" max= "> </progress>"
This in the browser will present a progress bar, now we have to do is to upload, real-time to change its value, and then the progress of the problem is presented to it.
We do not need to modify the server side, just want to xhr in JS object plus an event.
Xhr.upload.addEventListener ("Progress", progressfunction, False)
Progressfunction is invoked when it is passed into an event object that has two properties, one is the loaded one is total, respectively, the uploaded value, and the value to be uploaded.
That's exactly what we need, so this method can be written like this:
function Progressfunction (evt) {
var ProgressBar = document.getelementbyidx_x_x ("ProgressBar");
if (evt.lengthcomputable) {
Progressbar.max = evt.total;
Progressbar.value = evt.loaded;
}
This can be done, upload progress shows.
The following is an adjustment for the first example code above:
Example code 2 with a progress display:
The program that receives files in the background can be written in any language (C#,php,python, etc.), the above example uses C #
It's simply not necessary to make any changes to the progress bar.
var flist = request.files;
for (int i = 0; i < flist. Count; i++)
{
string FilePath = "E:\\hooyes\\files\\";
var c = flist[i];
FilePath = Path.Combine (FilePath, c.filename);
C.saveas (FilePath);
}
The above is a small set to introduce the jquery Ajax way to upload files, hope to help everyone, if you have any questions welcome to my message, small series will promptly reply to everyone!