Tasvirni ma'lumotlar bazasida saqlash va uni MVC 5 da Views-ga qanday ko'rsatish mumkin?

Quyidagi kabi jadval bor

CREATE TABLE [dbo].[Movies] (
[fname] NVARCHAR(50) NULL, 
[lname] NVARCHAR(50) NULL,
[MoviePoster] VARCHAR (50)  NULL,

kino afishasi maydoniga rasmni qanday saqlash va uni qanday ko'rish mumkinligi

3
qo'shib qo'ydi muallif Murat Yıldız, manba

6 javoblar

Serverda kino afisherni tejash haqida qanday fikrdaman:

/content/images/movieposters/thearrival.jpg

and storing in MoviePoster field only the filename thearrival.jpg

Shaxsan men bu yondashuvni afzal ko'rmoqdaman, chunki ma'lumotlar bazasi o'sib boradi va siz ko'proq tashrif buyurasiz ... yaxshi, siz barcha kino afishalarini boshqa serverga ko'chirishingiz va dastur serveridan ko'p yukni ozod qilish imkoniga ega bo'lasiz.

1
qo'shib qo'ydi
  [MoviePoster]      [varbinary](max) NULL

- Rasmni BLOB sifatida qo'shishingiz kerak - Blob skriptini qo'shing:

INSERT INTO [Movies](MoviePoster) 
VALUES (SELECT * FROM OPENROWSET (BULK 'your img url', SINGLE_BLOB))

- Tasvirlardagi tasvirni aks ettirish:


1
qo'shib qo'ydi
  1. Solution explorer'da "Images" papkasini yarating.
  2. ADO.NET ma'lumotlar bazasi modelini yaratish (ushbu misolda "Database1Entities")

Boshqarish vositasi

  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();
 }
 }
 }

Ko'rsatkichlar ko'rinishi

@{
 ViewBag.Title = "Index";
}

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
                new { enctype = "multipart/form-data" }))
 {
 <div>
 First name
@Html.TextBox("fname")
Last name
@Html.TextBox("lname")
Image
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" /> </div> }

Displeyni ko'rish

@{
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>             </td>
        <td>@item.fname</td>
        <td>@item.lname</td>
    </tr>
 }
  </tbody>
 </table>
}

OutPut ma'lumotlar bazasidan olingan rasmga ega bo'lgan jadval bo'ladi

1
qo'shib qo'ydi
  [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();
    }
0
qo'shib qo'ydi
INDEX


@{
    ViewBag.Title = "Index";
}


<link href="~/bootstrapp/css/bootstrap.min.css" rel="stylesheet" />
<script src="~/bootstrapp/js/bootstrap.min.js"></script>

Index

@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>@*<input type="number" name="candidateID" />*@</td></tr>
           <tr>           
            <td style ="width:10px;height:10px">                
                    <input type="text" name="Name" />
            </td>
            <td style="width:80px;height:50px">
                <input type="file" name="file1" id="file1" style="width: 100%;" /> 
</td> </tr> <tr> <td> <input type="text" name="address" /> </td> <td> <input type="file" name="file2" id="file2" style="width: 100%;" /> </td> </tr> <tr> <td> <input type="text" name="JobProfile" /> </td> <td> <input type="text" name="email" /> </td> </tr> <tr><td> <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>
@{
    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">
            @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);

            }
            else {    }        </td>        
    </tr>
    <tr>
        <td>
                 @detail.address       </td>
        <td>
            @if(@detail.PathPhoto!=null){        
            }else{            }       </td>
    </tr>
    <tr>
        <td>
            @detail.JobProfile </td>
        <td>
                      @detail.email </td>
    </tr>
        <tr><td></td><td>
@detail.phone</td><</tr>
    }
</table>
0
qo'shib qo'ydi

Aslida tasvirni Db da saqlashingiz mumkin. Siz istamasangiz, uni serverda fayl sifatida saqlashingiz shart emas (agar sizda ko'p filmlar mavjud bo'lsa, bu sizni boshqarish uchun muammo bo'lishi mumkin).

SQL Server dan foydalanayotgan bo'lsangiz, "rasm" ma'lumotlar turi mavjud. MySql-dan foydalanayotgan bo'lsangiz BLOB-dan foydalaning.

MVC foydalanayapman, shuning uchun:

Model (qisman kod) (SqlServer-da tasvirni e'lon qilasiz, modeldagi bunday bayt []:

public byte[] PersonImage { get; set; }

Xuddi shu modeldagi yo'lni olish uchun sizga kerak bo'lgan usul kerak bo'ladi:

public string GetPicture()
    {
        if (PersonImage == null)
        {
            return null;
        }

        var base64Image = System.Convert.ToBase64String(PersonImage);
        return $"data:{ImageContentType};base64,{base64Image}";
    }

Tekshiruvchi ichidagi xatti-harakatlarni yaratishga (Ilovani deklaratsiya qilish uchun IFormFile PersonImage kerak), mening ishimda, men nazorat boshqaruvchimning ro'yxatga olish jarayonida yuklamani ko'rib chiqaman (ba'zi nazorat kodlari qisqartirildi) :

 public async Task 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();

Va endi ko'rinish, siz formaga enktype qo'shishingiz kerak:

<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">
            

Create a new account.

            

            <div asp-validation-summary="All" class="text-danger"></div>

            <div class="form-group">
                
                <input type="file" asp-for="@person.PersonImage" class="form-control" />
                
            </div>


            <button type="submit" class="btn btn-default">Register</button>
        </form>
    </div>
    <div class="col-md-4"></div>
</div>

Shunga qaramay, kodning ko'p qismini yaxshi va qisman misol qilib oldim. Men JBga ba'zi tasvirlarni suratga olishga urinib ko'rganimda buni topish qiyin bo'ldi.

0
qo'shib qo'ydi