How to save Images to database using ASP.NET Core?

后端 未结 3 1598
攒了一身酷
攒了一身酷 2020-12-09 17:51

I am working on a small blog using ASP.NET Core(MVC 6) EF Visual Studio. I have trouble finding how to save images to a database. I have read about IFormfile bu

3条回答
  •  渐次进展
    2020-12-09 18:23

    You can use IFormFile to save image posted from view. Below is the sample code.

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

    In view simply bind it with IFormFile property like:

    User Logo
    
    

    In your controller you just need to save file on server like:

    var filename = ContentDispositionHeaderValue
                                        .Parse(user.UploadedImage.ContentDisposition)
                                        .FileName
                                        .Trim('"');
                        filename = Path.Combine(webRoot, "/Content/UserProfile/", $@"\{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;
    

提交回复
热议问题