Can I use the following jQuery code to perform file 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 to fill data part? Is it the correct way? I only POST the file to the server side.
Đang xem: How to upload files asynchronously using jquery?
I have been googling around, but what I found was a plugin while in my plan I do not want to use it. At least for the moment.
File upload is not possible through AJAX.You can upload file, without refreshing page by using IFrame.You can check further details here.
UPDATE
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: Phần Mềm Igas – Phần Mềm Quản Lý Bán Hàng Online
FormData support starts from following desktop browsers versions.
IE 10+Firefox 4.0+Chrome 7+Safari 5+Opera 12+
For more detail, see MDN link.
Iframes is no longer needed for uploading files through ajax. I”ve recently done it by myself. Check out these pages:
Using HTML5 file uploads with AJAX and jQuery
Updated the answer and 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.file.type;};Upload.prototype.getSize = function() { return this.file.size;};Upload.prototype.getName = function() { return this.file.name;};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) { var percent = 0; var position = event.loaded || event.position; var total = event.total; var progress_bar_id = “#progress-wrp”; if (event.lengthComputable) { percent = Math.ceil(position / total * 100); } // update progressbars classes so it fits your code $(progress_bar_id + ” .progress-bar”).css(“width”, +percent + “%”); $(progress_bar_id + ” .status”).text(percent + “%”);};How to use the Upload class
//Change id to your id$(“#ingredient_file”).on(“change”, function (e) { var file = $(this)<0>.files<0>; var upload = new Upload(file); // maby check size or type here with upload.getSize() and upload.getType() // execute upload upload.doUpload();});Progressbar html code