Friday, April 29, 2016

File Upload uisng Jquery in C# ASP.Net MVC

There so many ways to upload files with jqueries in ASP.Net C#. One way is with creating XMLHttpRequest and another way is with FormData object.
In this post i'll show uploading files and saving form data in one ajax call using jquery.


Upload Files with Jquery in ASP.Net MVC C#

First code for View which represents normal html code of form

@model modelname



MVC Controller Code for Saving File
In controller create action method with two arguments one is for formdata and another one is for List of HttpPostedFileBase Class which represents multiple files that you select.
public JsonResult SaveFilesWithFormData(ModelName FormData, List Of HTTPPostedFileBase Files) //Model Name represents class provided in view
{           
    try
    {
        //logic for saving data into database

        //save multiple files
        foreach (var upload in File)
        {
            if (upload != null)
            {
                 string pathToSave = "folderpath";

                 //Check folder is exist or not if not then it will creates folder
                 if (!Directory.Exists(pathToSave))
                 {
                     Directory.CreateDirectory(pathToSave);
                 }

                 //get file name for selected file            
                 string filename = Path.GetFileName(upload.FileName);

                 //save file
                 upload.SaveAs(pathToSave + filename);
            }
        }
        msg = "Success";
    }
    catch (Exception ex)
    {
        Log.Error(ex.Message);
    }
    return Json(msg, JsonRequestBehavior.AllowGet);
}

Hope that above code will help you to save files easily with form data into server. Keep coding

Saturday, April 2, 2016

Display image from byte array in ASP.NET MVC

There are many ways to display image from byte array in MVC as well as normal ASP.Net projects.In this post I'll explain couple of them.

1) Using BASE64 string of the image through ViewBag 

The first way is by sending a Base64 string as dataURL through ViewBag. As shown in below action method under consideration generates such a Base64 string of the image (often called Data URL) and then pass it to the view via a ViewBag property in MVC.
public ActionResult Image()
{
    string path = Server.MapPath("~/images/computer.png");
    byte[] imageByteData = System.IO.File.ReadAllBytes(path);
    string imageBase64Data=Convert.ToBase64String(imageByteData);
    string imageDataURL= string.Format("data:image/png;base64,{0}", imageBase64Data);
    ViewBag.ImageData = imageDataURL;
    return View();
}
The above code is a action method of Controller. In this action method it uses physical path of image and read all bytes of that image using ReadAllBytes() method. Once it read all bytes of that image in form of byte array,it will converts that byte array into base64 string format.

This converted base64 string is used to generate dataURL as shown in code. Take care of not to forget to append data:image/png;base64 at beginning of base64 string as shown.This way the browser knows that the src attribute value itself contains the image data. and at last assign value of dataURL to ViewBag.and then just below line in View to use that ViewBag.
 
Output :


2) By Sending Image File as ActionResult

In this approach it will reads byte array from image physical path and creates one file, after this it will send that file as result of action method in Controller.
public ActionResult GetImageFile()
{
    string path = Server.MapPath("~/images/computer.png");
    byte[] imageByteData = System.IO.File.ReadAllBytes(path);
    return File(imageByteData, "image/png"); 
}
To use the GetImageFile() action method you have to write below line in View:
<img src='@Url.Action("GetImageFile", "Home")'/>
Hope this will help you.