How To Upload File In Ajax? Step By Step Guide

Can I use the following jQuery code to lớn persize tệp tin upload using POST method of an ajax request ?

$.ajax( type: "POST", timeout: 50000, url: url, data: dataString, success: function (data) alert("success"); return false; );If it is possible, do I need khổng lồ fill data part? Is it the correct way? I only POST the file khổng lồ the server side.

Bạn đang xem: How to upload file in ajax? step by step guide

I have been googling around, but what I found was a plugin while in my plan I vày not want to lớn use it. At least for the moment.



File upload is not possible through AJAX.You can upload tệp tin, without refreshing page by using IFrame.You can check further details here.


With XHR2, File upload through AJAX is supported. E.g. through FormData object, but unfortunately it is not supported by all/old browsers.

Xem thêm: Không Điều Trị Ung Thư Nội Mạc Tử Cung Qua Dấu Hiệu Và Cách Điều Trị

FormData support starts from following desktop browsers versions.

IE 10+Firefox 4.0+Chrome 7+Safari 5+Opera 12+

For more detail, see MDN links.



Iframes is no longer needed for uploading files through ajax. I"ve sầu recently done it by myself. Cheông xã out these pages:

Using HTML5 tệp tin uploads with AJAX & jQuery

Updated the answer và cleaned it up. Use the getSize function to check size or use getType function to check types.Added progressbar html and css code.

var Upload = function (file) this.file = file;;Upload.prototype.getType = function() return this.tệp tin.type;;Upload.prototype.getSize = function() return this.tệp tin.size;;Upload.prototype.getName = function() return;;Upload.prototype.doUpload = function () var that = this; var formData = new FormData(); // add assoc key values, this will be posts values formData.append("file", this.file, this.getName()); formData.append("upload_file", true); $.ajax( type: "POST", url: "script", xhr: function () var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) myXhr.upload.addEventListener("progress", that.progressHandling, false); return myXhr; , success: function (data) // your callback here , error: function (error) // handle error , async: true, data: formData, cache: false, contentType: false, processData: false, timeout: 60000 );;Upload.prototype.progressHandling = function (event) ;How to lớn use the Upload class

//Change id lớn your id$("#ingredient_file").on("change", function (e) var tệp tin = $(this)<0>.files<0>; var upload = new Upload(file); // maby check kích thước or type here with upload.getSize() và upload.getType() // execute upload upload.doUpload(););Progressbar html code