upload images in database as varbinary asp.net

Store images in SQL Server using EF Cadre and ASP.Cyberspace Cadre

At times y'all need to store images in a data store rather than storing them every bit physical files. You tin can shop them in and retrieve them from SQL Server using Entity Framework Core and ASP.NET Core. This article shows yous how.

In order to work through this instance, you need a SQL Server table called Images every bit shown below:

As you tin can see in that location are three columns namely Id, ImageTitle, and ImageData. The ImageTitle column stores a string containing title or name of an image. The ImageData column stores the actual image information. This column has its type ready to varbinary(MAX) since image is a binary data.

Ok. At present advertisement NuGet parcel for EF Core provider for SQL Server - Microsoft.EntityFrameworkCore.SqlServer.

Once you add the EF Core provider for SQL Server, you lot demand to create Entity Framework Core model consisting of a DbContext class and an entity class. The Prototype entity class is shown beneath:

public class Image {     public int Id { go; set; }     public string ImageTitle { get; set; }                      public byte[] ImageData { get; set; }          }

The Image grade is a POCO and follows conventions to map with the underlying Images table schema. Notice that ImageData property is a byte array that stores binary image data.

The AppDbContext class is shown below:

public form AppDbContext:DbContext {     public AppDbContext(DbContextOptions <AppDbContext> options) : base(options)     {     }                      public DbSet<Image> Images { go; fix; }          }

You also demand to annals AppDbContext with ASP.Net Cadre's DI framework. This is done inside ConfigureServices() method of the Startup course as shown beneath:

public void ConfigureServices(IServiceCollection services) {     services.AddControllersWithViews();                      services.AddDbContext<AppDbContext>(o =>     {         o.UseSqlServer("data source=.;         initial catalog=MyImagesDb;         integrated security=true");     });          }

So far so adept. Side by side, we will create a <form> that allows usa to upload images files to the server. This grade is shown below:

<form asp-activeness="UploadImage"        asp-controller="Home"        method="mail"          enctype="multipart/form-information">     <input type="file" id="file1"             proper noun="file1"             multiple="multiple" />     <button type="submit">Upload File(s)</push> </form>

This form is quite simple and straightforward. Detect that the enctype attribute is set to multipart/course-data since yous are uploading files from the client to the server. Clicking on the Upload Files button submits the form to the UploadImage() activeness. The UploadImage() action is showb below:

[HttpPost] public IActionResult UploadImage() {     foreach(var file in Request.Class.Files)     {         Image img = new Image();         img.ImageTitle = file.FileName;                      MemoryStream ms = new MemoryStream();         file.CopyTo(ms);         img.ImageData = ms.ToArray();                    ms.Close();         ms.Dispose();                      db.Images.Add(img);         db.SaveChanges();                    }     ViewBag.Bulletin = "Image(south) stored in  database!";     return View("Index"); }

The UploadImage() action iterates through the uploaded files. This is done using the Request.Form.Files drove. Within the foreach loop, an Image object is created and its ImageTitle belongings is set to the file name of the image. The file proper name of an image is obtained from the FileName holding of IFormFile object.

We are more than interested in the image data. To grab the image information the code creates a MemoryStream and copies the uploaded image data into information technology using the CopyTo() method. The MemoryStream is converted into a byte assortment using its ToArray() method. This byte array is stored in the ImageData property of the Image object.

The newly created Paradigm entity is added to the Images DbSet and SaveChanges() method is called to save the data to the underlying database. This saves the uploaded image into the Images tabular array of SQL Server.

Now let'south retrieve the image and display it on a view.

Add another <course> to the view as shown below:

<form asp-action="RetrieveImage"        asp-controller="Abode"        method="mail service">     <button type="submit">Show Latest Image</button> </form>

Information technology'south a simple form that has a submit push button and POSTs to RetrieveImage() action. The RetrieveImage() action is shown below:

[HttpPost] public ActionResult RetrieveImage() {                      Image img = db.Images.OrderByDescending (i=>i.Id).SingleOrDefault();     string imageBase64Data =  Convert.ToBase64String(img.ImageData);     string imageDataURL =                    string.Format("data:image/jpg;base64,{0}",  imageBase64Data);                    ViewBag.ImageTitle = img.ImageTitle;     ViewBag.ImageDataUrl = imageDataURL;     return View("Index"); }

Notice what's going on within the RetrieveImage() action. First, the code grabs a latest Image added to the database using SingleOrDefault() method. This image is is the course of a byte array and tin can't be displayed on the view directly. Then, the lawmaking converts the byte assortment into Base64 encoded string. This string is so used to form what is known as Prototype Data URL. Notice that image type is mentioned every bit jpg. Y'all should change it equally per your requirement.

The paradigm data URL is stored in ViewBag'south ImageDataUrl belongings. To brandish this prototype you lot can use the following markup.

<h1>@ViewBag.Message</h1> <h1>@ViewBag.ImageTitle</h1>          <img src="@ViewBag.ImageDataUrl" />        

As you can see the src attribute of <img> tag is assigned the ImageDataUrl value.

A sample run of this application is shown beneath:

That'southward it for now! Keep coding!!

huntpues2001.blogspot.com

Source: http://www.binaryintellect.net/articles/2f55345c-1fcb-4262-89f4-c4319f95c5bd.aspx

0 Response to "upload images in database as varbinary asp.net"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel