2017-03-11 135 views
5

我正在使用ASP.NET Core(MVC 6)EF Visual Studio的小型博客上工作。我无法找到如何将图像保存到数据库。我已经阅读了关于IFormfile的内容,但我并不真正了解如何去做,我被卡住了。我对此很陌生,并希望有一点帮助。如何使用ASP.NET Core将图像保存到数据库?

我想将图像保存到我创建的帖子中(以相同的形式)。因此,我想将它保存到postID中。然后我需要能够显示图像,我该怎么做?我知道还有很多要问,但我不知道该怎么转。如果您有任何好的提示或想法,请随时发送链接。

在此先感谢!

+0

将文件保存到数据库并不是一个好主意,您的数据库可能会变得很快,这使备份和恢复成为问题。 –

回答

0

您可以使用IFormFile保存从视图发布的图像。以下是示例代码。

public class UserProfileViewModel 
    { 
     public string UserName { get; set; } 
     public IFormFile UploadedImage { get; set; } 
     public string ImageUrl { get; set; } 
    } 

鉴于只需用IFormFile属性绑定它像:

<img src="@Model.ImageUrl" alt="User Logo" asp-append-version="true" /> 
<input type="file" asp-for="UploadedImage" /> 

在你的控制器,你只需要保存文件,像服务器:

var filename = ContentDispositionHeaderValue 
            .Parse(user.UploadedImage.ContentDisposition) 
            .FileName 
            .Trim('"'); 
        filename = Path.Combine(webRoot, "/Content/UserProfile/", [email protected]"\{filename}"); 
        if (Directory.Exists(webRoot + "/Content/UserProfile/")) 
        { 
         using (FileStream fs = System.IO.File.Create(filename)) 
         { 
          user.UploadedImage.CopyTo(fs); 
          fs.Flush(); 
         } 
        } 
model.ImageURL = "~/Content/Brands/" + user.UploadedImage.FileName; 
2

你会发现这个有用的,如果你需要保存到数据库。这是的https://www.mikesdotnetting.com/article/259/asp-net-mvc-5-with-ef-6-working-with-files的修改和大量投入,从这里k7Boys回答MVC 6 HttpPostedFileBase?

<input type="file" name="Image" id="Imageinput"> 

博客莫代尔类应该有图场等;

public int BlogId{ get; set; } 
    ... 
    public byte[] Img{ get; set; } 

控制器;

public async Task<IActionResult> Create([Bind("BlogId,...Img")] Blog blog t, IFormFile Image) 
    if (ModelState.IsValid) 
     { 
      if (Image!= null) 

      { 
       if (Image.Length > 0) 

       //Convert Image to byte and save to database 

       { 

        byte[] p1 = null; 
        using (var fs1 = Image.OpenReadStream()) 
        using (var ms1 = new MemoryStream()) 
        { 
         fs1.CopyTo(ms1); 
         p1 = ms1.ToArray(); 
        } 
        Blog.Img= p1; 

       } 
      } 

      _context.Add(client); 
      await _context.SaveChangesAsync(); 

      return RedirectToAction("Index"); 
     } 

花了我几个小时才到这里。现在正在查看视图中的图像,确保这不会很复杂。享受

相关问题