Pages

Thursday, April 7, 2011

Implement File upload using ASP.NET MVC2,0 and AjaxFileUploader

This blog explains implemention of file upload using ASP.NET MVC2.0

In MVC, generally to retrieve the controlls value in th post method we either use form collection or pass a parameter in the post mehtod with the name of the control. Now this parameter will have the value of the control. But this is slightly different while using file uploader expecially for mapping to virtual path.

Concept:
  1. Create the html code for uplaoder and display tje list of file.
  2. Define the javascript to be called on upload click. Which helps to read the uploaded file. And finally display in the list.

To implement, here we use ajax file uploader. Thus in aspx give the following.

For file upload control : 
< input type="file" id="document" name="document" />
The above code renders the uploader control.

input type="submit" name="Submit" id="Submit" value="Upload" onclick="UploadFile()" />
 The above code renders a button, which calls the javascript UploadFile on the button click.


table id="tblAttachments" cellpadding="3" cellspacing="0"
  tr
     td   /td
  /tr
/table
The above code is used to list the uploaded file names in a table formate.

In javascript the UploadFile() is defined as below:
 function UploadFile() {      
    if ($("#document").val() == '') {   //this is called when no file is been selected          
           alert('Please select a valid document.');
           return false;
     }
     $.ajaxFileUpload({
          
          url: "< % = Url.Content("~/Sample/CreateAttachment_Post") %  >;", // For any parameters use - + "?param1=" + document.getElementById('id').value, 
          data: { val: 'aaa' },
          secureuri: false,
          fileElementId: 'document',
          dataType: 'xlm',
          
          success: function (data, status) { //On success append the data to the table. This avoid the DB interaction once again for retrival after the upload.
               //The following code helps to add the uploaded file to the list display using the table tblAttachments.
              
               var appendString = "tr";
               appendString += ' td class="attach" id="ttt' + data + '" style="text-align:left;"> /td /tr';
               $("#tblAttachments tr:last").after(appendString);
               $("#tblAttachments tr:last").children(".attach").text(data);
           },
          
           error: function (data, status, e) { // For any errors or exceptions.               alert(e);
           }
    });
    return false;
}

This ajaxFileUpload is used to retrieve the virtual file path of the uploaded file. to use this method, need to include ajaxFileUpload.js.
      The above ajax code helps to call a method from controller by using the URL property. in URL we define the controller name and the method to be called.
      Any parameters could be passed using the querystring logic or by usig the data property.
      Here the fileElementId property defines the fileUpload control name which would be retrieved in the method called from URL.
      The Success is called on successfull execution of the method called by URL and the returned values of the method can be retrieved here using function (data, status) . wherein the data contains the returned value.
      In the above example, on successfull execution of the method we add the uploaded file name to the list displayed in the table format.
    Any exceptions could be caught with the help of error property.

Now in the controlelr part we need to define the
CreateAttachment_Post method which is called by the ajaxFileUpload.
The following code defines the CreateAttachment_Post

public void CreateAttachment_Post()
{       
        try
       {
              string fileName = string.Empty;
              foreach (string upload in Request.Files)  // all those file uplod controls defined in fielElementId property will get included in the Request.Files.             {
                   string mimeType = Request.Files[upload].ContentType;
                   Stream fileStream = Request.Files[upload].InputStream;
                   int fileLength = Request.Files[upload].ContentLength;
                   byte[] fileData = new byte[fileLength];
                   fileStream.Read(fileData, 0, fileLength);
                   fileStream.Close();
                   fileName = Request.Files[upload].FileName.Substring(Request.Files[upload].FileName.LastIndexOf(@"\") + 1, Request.Files[upload].FileName.Length - (Request.Files[upload].FileName.LastIndexOf(@"\") + 1));
                   Response.Write(fileName);                
           }
      }
      catch (Exception ex)
      {
                 throw ex;
      }
}

No comments:

Post a Comment