MVC- upload and Save Images as a String (Image To Base64String)
Step1: index.cshtml
@using (Html.BeginForm("UserRegister", "UserRegistration", FormMethod.Post, new { enctype = "multipart/form-data", @class = "msform", role = "form" }))
{
<div class="col-md-6 col-md-offset-3">
<center><div id="dvPreview" name="dvPreview" class="prw"><img id="imgPreview" name="imgPreview" src="~/images/Browse.png" style="padding: 10px;border-radius: 100%;margin-bottom: 20px;" /></div></center>
<input type="file" id="img" name="img" />
<center><input type="submit" id="btnSubmit" value="Next" class="next action-button" /> </center> </div>
}
step2: controller.cs
using System.Drawing.Imaging;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
public ActionResult UserRegister(HttpPostedFileBase img)
{
if (ModelState.IsValid)
{
if (img == null)
{
ModelState.AddModelError("File", "Please Upload Your file");
}
else if (img.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 3; //3 MB
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".PNG", ".JPG", ".GIF" };
if (!AllowedFileExtensions.Contains(img.FileName.Substring(img.FileName.LastIndexOf('.'))))
{
ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
}
else if (img.ContentLength > MaxContentLength)
{
ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
}
else
{
if (Request.Files.Count > 0)
{
if (Request.Files[0].ContentLength > 0)
{
byte[] buf; // byte array
Stream stream = img.InputStream; //initialise new stream
buf = new byte[stream.Length]; //declare arraysize
stream.Read(buf, 0, buf.Length); // read from stream to byte array
string ProfileImage = Convert.ToBase64String(buf);
Session["Image"] = ProfileImage.ToString(); }
}
}
}
}
return RedirectToAction("UserRegisterStep2", "UserRegistration");
}
MVC- Display Images from (Base64String to Images)
Ste1:index.cshtml
<img src="data:image/jpg;base64,' + TEST + '" name="imgPreview" class="img-rounded" id="center_images" />
step2: controller.cs
Model.TEST ="string from Databse";
No comments:
Post a Comment