Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Ajax File Upload

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.

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.

like image 808
Willy Avatar asked Feb 23 '10 16:02

Willy


People also ask

How to upload a file via AJAX?

Ajax file uploadsA JavaScript method must be coded to initiate the asynchronous Ajax based file upload; A component must exist on the server to handle the file upload and save the resource locally; The server must send a response to the browser indicating the JavaScript file upload was successful; and.


2 Answers

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.

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.

like image 112
Adeel Avatar answered Nov 18 '22 09:11

Adeel


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

http://dev.w3.org/2006/webapi/FileAPI/#FileReader-interface

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

<div id="progress-wrp">     <div class="progress-bar"></div>     <div class="status">0%</div> </div> 

Progressbar css code

#progress-wrp {   border: 1px solid #0099CC;   padding: 1px;   position: relative;   height: 30px;   border-radius: 3px;   margin: 10px;   text-align: left;   background: #fff;   box-shadow: inset 1px 3px 6px rgba(0, 0, 0, 0.12); }  #progress-wrp .progress-bar {   height: 100%;   border-radius: 3px;   background-color: #f39ac7;   width: 0;   box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.11); }  #progress-wrp .status {   top: 3px;   left: 50%;   position: absolute;   display: inline-block;   color: #000000; } 
like image 22
JohannesAndersson Avatar answered Nov 18 '22 10:11

JohannesAndersson