Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to upload a file using Asp.Net MVC and AJAX?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 678
    Comment on it

    In this blog we illustrate how we can upload a file using ASP.Net MVC and AJAX.

     

    Follow the below steps to upload a file:

     

    1. Firstly we need to create model which contains the properties such as name, length and type of the file.

     

    See the below code for creating a model:

     

    public class UploadFiles
    {
        public string FileName { get; set; }
        public int FileLength { get; set; }
        public string FileType { get; set; }
    }

     

    2. Create a Action method in controller which is a HttpPost method to post the list of selected files and save into the specified path.

     

    See the below code for creating a Action method:

    [HttpPost]
    public ContentResult FileUpload()
    {
            var UploadFile = new List<UploadFiles>();
     
            foreach (string file in Request.Files)
            {
                    HttpPostedFileBase hp = Request.Files[file] as HttpPostedFileBase;
                    if (hp.ContentLength == 0)
                            continue;
     
                    string fileName =Path.Combine(Server.MapPath("~/Content/Images"), Path.GetFileName(hp.FileName));
                    hp.SaveAs(fileName);
     
                    UploadFile.Add(new UploadFiles()
                    {
                            FileName = hp.FileName,
                            FileLength = hp.ContentLength,
                            FileType = hp.ContentType
                    });
            }
            return Content("{\"name\":\"" + UploadFile[0].FileName + "\",\"type\":\"" + UploadFile[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", UploadFile[0].FileLength) + "\"}", "application/json");
    }

     

    3. Download the jQuery plugin (jquery.fileupload.css and jquery.fileupload.js) for file upload.

     

    4. Create a view for uploading a file.

    <div class="container">
    		<span class="btn btn-success fileinput-button">
    			<i class="glyphicon glyphicon-plus"></i>
    			<span>Upload files</span>
    			<input id="fileupload" type="file" name="files[]" multiple>
    		</span>
    		<br />
    		<div class="progress">
    			<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
    				<span class="sr-only">0% complete</span>
    		</div>
    		</div>
    		<br />
    		<div class="fileName"></div>
    		<br />
    		<div class="fileType"></div>
    		<br />
    		<div class="fileSize"></div>
    	</div>

     

    5. Add the below code for the Script section of the Ajax call which calls the Action Result method FileUpload create in our controller.

     <script type="text/javascript">
    	$(document).ready(function () {
    		$('#fileupload').fileupload({
    			dataType: 'json',
    			url: '/Home/FileUpload'
    			autoUpload: true,
    			done: function (e, data) {
    				$('.filename').html(data.result.name);
    				$('.filetype').html(data.result.type);
    				$('.filesize').html(data.result.size);
    			}
    		}).on('fileuploadprogressall', function (e, data) {
    			var progress = parseInt(data.loaded / data.total * 100, 10);
    			$('.progress .progress-bar').css('width', progress + '%');
    		});
    	});
      </script>
    

     

    6. Add the following references in head section of the view page.

            <link href="~/Content/bootstrap/bootstrap.min.css" rel="stylesheet" />
    	<link href="~/Content/bootstrap/bootstrap-theme.min.css" rel="stylesheet" />
    	<link href="~/Content/jquery.fileupload.css" rel="stylesheet" />
    	<script src="~/Scripts/jquery-1.9.1.min.js"></script>
    	<script src="~/Scripts/jquery.ui.widget.js"></script>
    	<script src="~/Scripts/bootstrap.min.js"></script>
    	<script src="~/Scripts/jquery.fileupload.js"></script>

     

    7. Run the application on web browser.

     

    Conclusion:

    When you run the above code in web browser you get a 'Add Files....' button, Click on this button 'Open' screen will popup where you can choose your file, after choosing the file you see the FileName, FileType and FileSize on web browser then open your 'Image' folder where the uploaded file is saved.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: