I have a table like following
CREATE TABLE [dbo].[Movies] (
[fname] NVARCHAR(50) NULL,
[lname] NVARCHAR(50) NULL,
[MoviePoster] VARCHAR (50) NULL,
how to save image to movie poster field and how to view it
I have a table like following
CREATE TABLE [dbo].[Movies] (
[fname] NVARCHAR(50) NULL,
[lname] NVARCHAR(50) NULL,
[MoviePoster] VARCHAR (50) NULL,
how to save image to movie poster field and how to view it
[MoviePoster] [varbinary](max) NULL
-- You have to insert image as a BLOB -- Insert blob script :
INSERT INTO [Movies](MoviePoster)
VALUES (SELECT * FROM OPENROWSET (BULK 'your img url', SINGLE_BLOB))
--Display image in views:
<img src='data:image/jpeg;base64, <--data from db-->' />
How about saving movie poster on your server let's say:
/content/images/movieposters/thearrival.jpg
and storing in MoviePoster
field only the filename thearrival.jpg
I personally prefer this approach because if let's say your database will grow and you will have more visitors ...well, you will be able to move all your movie posters to a different server and free up a lot of load from application server.
Home Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace test2.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
Database1Entities db = new Database1Entities();
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath =Server.MapPath("~/images/"+ ImageName);
// save image in folder
file.SaveAs(physicalPath);
//save new record in database
tblA newRecord = new tblA();
newRecord.fname = Request.Form["fname"];
newRecord.lname = Request.Form["lname"];
newRecord.MoviePoster = ImageName;
db.tblAs.Add(newRecord);
db.SaveChanges();
}
//Display records
return RedirectToAction("../home/Display/");
}
public ActionResult Display()
{
return View();
}
}
}
Index View
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div>
First name<br />
@Html.TextBox("fname") <br />
Last name<br />
@Html.TextBox("lname") <br />
Image<br />
<input type="file" name="file" id="file" style="width: 100%;" /> <br />
<input type="submit" value="Upload" class="submit" />
</div>
}
DisplayView
@{
ViewBag.Title = "Display";
}
@{
test2.Database1Entities db = new test2.Database1Entities();
}
@using (Html.BeginForm())
{
<table border="1">
<thead>
<tr>
<th>Image</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
@foreach (var item in db.tblAs)
{
<tr>
<td><img src="~/images/@item.imageUrl" width="100" height="100" /> </td>
<td>@item.fname</td>
<td>@item.lname</td>
</tr>
}
</tbody>
</table>
}
The OutPut will be a table with viewed image from the database
Actually you can store the image on Db as well. You don't need to keep it on the server as a file if you don't want to (if you have lots of movies it would be a problem to manage).
If you are using SQL Server there is a "image" data type. If you are using MySql you should use BLOB.
I am using MVC, so:
The Model (partial code) (while in SqlServer you will declare image, inside the model the type will be byte[]:
public byte[] PersonImage { get; set; }
Inside the same model you are going to need a method to retrieve the path:
public string GetPicture()
{
if (PersonImage == null)
{
return null;
}
var base64Image = System.Convert.ToBase64String(PersonImage);
return $"data:{ImageContentType};base64,{base64Image}";
}
The create action inside the controller (The action declaration will need to receive an IFormFile PersonImage), on my case I am handling the image upload on the register action of my controller (Some of the controller code has been taken off to be more concise):
public async Task<IActionResult> Register(RegisterViewModel model, Client client, Employee employee, Person person, IFormFile PersonImage, string returnUrl = null)
if (PersonImage != null)
{
using (var stream = new MemoryStream())
{
await PersonImage.CopyToAsync(stream);
person.PersonImage = stream.ToArray();
person.ImageContentType = PersonImage.ContentType;
}
}
_context.Add(person);
await _context.SaveChangesAsync();
And now the view, you need to add the enctype to the form:
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<form asp-route-returnUrl="@ViewData["ReturnUrl"]" method="post" enctype="multipart/form-data">
<h2 class="text-center font-weight-bold">Create a new account.</h2>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="@person.PersonImage" class="control-label"></label>
<input type="file" asp-for="@person.PersonImage" class="form-control" />
<span asp-validation-for="@person.PersonImage" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-default">Register</button>
</form>
</div>
<div class="col-md-4"></div>
</div>
Again, I took off most of the code to get a better and concise example. I had a hard time to find this when I was trying to put some images to the Db.
[HttpPost]
public ActionResult AddEmployee(HttpPostedFileBase file)
{
using(DbEntities DB = new DbEntities())
{
TblImage tblimg=new TblImage();
if (file != null)
{
var fileName = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("~/Data/EmployeeProfileImage/" + fileName));
tblimg.image = "~/Data/EmployeeProfileImage/" + fileName;
}
DB.TblImages.Add(tblimg);
DB.SaveChanges();
}
return View();
}
INDEX
@{
ViewBag.Title = "Index";
}
<link href="~/bootstrapp/css/bootstrap.min.css" rel="stylesheet" />
<script src="~/bootstrapp/js/bootstrap.min.js"></script>
<style>
table, th, td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
<h2>Index</h2>
@using (Html.BeginForm("Index", "Candidate", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div class="container">
<table>
<tr><td colspan="2" style="width:800px;height:50px">candidate</td></tr>
<tr><td>@*<label>Id</label><input type="number" name="candidateID" />*@</td></tr>
<tr>
<td style ="width:10px;height:10px">
<label>Name</label> <input type="text" name="Name" />
</td>
<td style="width:80px;height:50px"><label>Binary Image</label>
<input type="file" name="file1" id="file1" style="width: 100%;" /> <br />
</td>
</tr>
<tr>
<td>
<label>Address</label> <input type="text" name="address" />
</td>
<td>
<label>Path Image</label> <input type="file" name="file2" id="file2" style="width: 100%;" />
</td>
</tr>
<tr>
<td>
<label>JobProfile</label> <input type="text" name="JobProfile" />
</td>
<td>
<label>Email</label> <input type="text" name="email" />
</td>
</tr>
<tr><td>
<label>Phone No.</label> <input type="number" name="phone" />
</td><td ><input type="submit" value="Submit"/></td></tr>
</table>
</div>
}
@Html.Partial("~/Views/Candidate/detail.cshtml")
DETAIL
@*@model List< angularmvcdemo.CandidateDetail>*@
@using angularmvcdemo.Models;
<link href="~/bootstrapp/css/bootstrap.min.css" rel="stylesheet" />
<script src="~/bootstrapp/js/bootstrap.min.js"></script>
<style>
table, th, td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
@{
modeldataEntities db = new modeldataEntities();
//angularmvcdemo.modeldataEntities db = new angularmvcdemo.modeldataEntities();
}
<table>
<tr><td colspan="2" style="width:800px;height:50px">candidate</td></tr>
@foreach(var detail in db.CandidateDetails){
<tr>
<td style="width:10px;height:10px">
<label>Name</label>@detail.Name
@*<input type="text" name="Name" />*@ </td>
<td> binary image
@if (detail.BinaryPhoto != null)
{ var base64 = Convert.ToBase64String(detail.BinaryPhoto);
var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);
<img src='@imgsrc' style="max-width:100px;max-height:100px" />
}
else { <img src="~/img/avatar-default.jpg" style="max-width:100px;max-height:100px" /> } </td>
</tr>
<tr>
<td>
<label>Address</label> @detail.address </td>
<td><label>path image</label>
@if(@detail.PathPhoto!=null){ <img src="@detail.PathPhoto" width="100" height="100" />
}else{ <img src="~/img/avatar-default.jpg" style="max-width:100px;max-height:100px" /> } </td>
</tr>
<tr>
<td>
<label>JobProfile</label>@detail.JobProfile </td>
<td>
<label>Email</label> @detail.email </td>
</tr>
<tr><td></td><td><label>Phone No.</label>
@detail.phone</td><</tr>
}
</table>