Asp Net Web Api Image Upload Save to Database Byte

Store images in SQL Server using EF Core and ASP.Net Core

At times you need to shop images in a data store rather than storing them as concrete files. You can store them in and call back them from SQL Server using Entity Framework Core and ASP.NET Core. This article shows y'all how.

In order to work through this instance, you demand a SQL Server table called Images equally shown below:

Equally you tin run across there are iii columns namely Id, ImageTitle, and ImageData. The ImageTitle cavalcade stores a string containing championship or name of an prototype. The ImageData column stores the actual image data. This column has its type set up to varbinary(MAX) since epitome is a binary information.

Ok. At present advertising NuGet package for EF Core provider for SQL Server - Microsoft.EntityFrameworkCore.SqlServer.

In one case you add the EF Core provider for SQL Server, you need to create Entity Framework Core model consisting of a DbContext class and an entity class. The Image entity class is shown below:

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

The Prototype class is a POCO and follows conventions to map with the underlying Images table schema. Observe that ImageData holding is a byte array that stores binary epitome information.

The AppDbContext form is shown below:

public class AppDbContext:DbContext {     public AppDbContext(DbContextOptions <AppDbContext> options) : base(options)     {     }                      public DbSet<Image> Images { get; prepare; }          }

Yous as well demand to register AppDbContext with ASP.Internet Core'south DI framework. This is washed inside ConfigureServices() method of the Startup class every bit shown below:

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

So far then good. Next, we will create a <grade> that allows us to upload images files to the server. This form is shown below:

<form asp-activeness="UploadImage"        asp-controller="Home"        method="postal service"          enctype="multipart/form-information">     <input type="file" id="file1"             name="file1"             multiple="multiple" />     <button type="submit">Upload File(southward)</button> </class>

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

[HttpPost] public IActionResult UploadImage() {     foreach(var file in Asking.Class.Files)     {         Image img = new Prototype();         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.Message = "Image(south) stored in  database!";     return View("Alphabetize"); }

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

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

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

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

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

<form asp-action="RetrieveImage"        asp-controller="Home"        method="post">     <button type="submit">Show Latest Image</button> </course>

It's a unproblematic form that has a submit button and POSTs to RetrieveImage() action. The RetrieveImage() activity is shown below:

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

Discover what'due south going on inside the RetrieveImage() activeness. First, the code grabs a latest Image added to the database using SingleOrDefault() method. This epitome is is the form of a byte array and can't exist displayed on the view straight. Then, the lawmaking converts the byte array into Base64 encoded string. This string is so used to form what is known as Image Data URL. Notice that image type is mentioned as jpg. Yous should modify information technology every bit per your requirement.

The image data URL is stored in ViewBag'due south ImageDataUrl property. To brandish this paradigm you can employ the following markup.

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

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

A sample run of this application is shown beneath:

That'due south information technology for at present! Go on coding!!

webbwassing.blogspot.com

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

0 Response to "Asp Net Web Api Image Upload Save to Database Byte"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel