The multiple attribute in HTML5 allows user to select multiple files from the browse window. Through ajax we can upload the selected files simultaneously. We can use XMLHttpRequest to upload the files to server asynchronously. The data transfer can be tracked with the event listeners.
By this we can know how much data is transferred to the server. This is useful when we want to show some progress bar to the user while the file is being uploaded. Here is the sample JavaScript code to send data asynchronously.
JavaScript:
- var requests = new Array();
- var xmlRequests = new Array();
- var xhr = new XMLHttpRequest();
- var uploadObj = xhr.upload;
- requests.push(uploadObj);
- xmlRequests.push(xhr);
- uploadObj.addEventListener("progress", function(ex) {
- var pc = parseInt(((ex.loaded / ex.total) * 100)); //tells how much percentage of data is uploaded.
- }
- }, false);
- xhr.open('POST', "Service Url", true);
- xhr.onreadystatechange = function(response) {
- if (this.readyState != 4) return;
- if (this.status == 200) {
- // called after file has been uploaded successfully
- }
- };
- xhr.send(data);
HTML:
- <form action="action url">
- Select images: <input type="file" name="file" multiple>
- <input type="submit">
- </form>
- public ActionResult UploadFiles(HttpPostedFileBase file) {
- string fileName = "";
- bool IsSucceeded = false;
- string Message = string.Empty;
- string path = Server.MapPath("~/Temp");
- fileName = new FileInfo(file.FileName).Name;
- if (file.ContentLength <= (2 * 1024 * 1024)) {
- file.SaveAs(path + "/" + fileName);
- IsSucceeded = true;
- } else {
- Message = "Failed: Max limit 2MB";
- }
- return Json(new {
- Success = IsSucceeded, Url = fileName, Message = Message
- });
- }
Hanumantha Reddy G SPosted Dec 22, 2016, 11:03 AM
Hi, could you please attach the code.
Cường HoàngPosted Nov 17, 2016, 12:18 PM
Attach file missing?. can you fix this?
Hanumantha Reddy G SPosted Jul 6, 2015, 6:45 AM
Working example code missing.
Hanumantha Reddy G SPosted Jul 3, 2015, 5:23 AM
Attachment missing.
Santhakumar MunuswamyPosted Jun 30, 2015, 2:37 PM
Nice