Controler Code
public static byte[] GetImageFromUpload()
{
HttpPostedFileBase postedFile = null;
if (HttpContext.Current.Request != null && HttpContext.Current.Request.Files.Count > 0)
postedFile = new HttpPostedFileWrapper(HttpContext.Current.Request.Files["imageUpload"]);
if (postedFile == null || postedFile.FileName == string.Empty) return null;
using (Image img = Image.FromStream(postedFile.InputStream))
{
var file = new byte[postedFile.InputStream.Length];
var reader = new BinaryReader(postedFile.InputStream);
postedFile.InputStream.Seek(0, SeekOrigin.Begin);
file = reader.ReadBytes((int)postedFile.InputStream.Length);
return file;
}
}
LoadEmployeeImageToObject() method can use to add the imege to Byte arry and parse it to server using session
public static void LoadEmployeeImageToObject(byte[] photo , int employeeId)
{
if (HttpContext.Current.Request != null)
{
byte[] uploadedImageFromFileControl = GetImageFromUpload();
bool removeImage = HttpContext.Current.Request["removeImage"] == "on";
if (HttpContext.Current.Session["AjaxPhoto"] != null)
{
photo = (byte[])HttpContext.Current.Session["AjaxPhoto"];
}
else if (uploadedImageFromFileControl != null) photo = uploadedImageFromFileControl;
else if (employeeId != 0) //load image from db
{
photo = photo;
}
}
}
if you are using this code no need to create database column for save image on database.just put a column for save picture id.using below jS script you can save image on server file system.(File path)
function uploadFile() {
var fd = new FormData();
fd.append("imageUpload", document.getElementById('imageUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "/HumanResource/Employee/AjaxImageUpload");//controller path
xhr.responseType = 'blob';
xhr.send(fd);
$('#divUploadStatus').show();
}
this JS method can bind with your patial view.chtml file like this
<div id="divUploadPanel">
<label>
Upload New Image:</label>
<input type="file" id="imageUpload" name="imageUpload" onchange=" uploadFile(); " /><br />
this is the code for parent chtml file
<div class="control-group">
<label class="control-label" >Photo</label>
<div class="controls">
@Html.Partial("_EditorImagePanel", Model)
</div>
</div>
Hope this will help to you.thanks :)