How to store image in database using asp.net core api?
Loading
How to store image in database using asp.net core api?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Vishal YelveRank #178 · 13.6K reputationPosted Oct 7, 2022, 8:43 AM EDT
Hi Tahir,
I am saving file at location and saving file name in db.
[Route("SaveFile")] [HttpPost] public JsonResult SaveFile() { try { var httpRequest = Request.Form; var postedFile = httpRequest.Files[0]; string filename = postedFile.FileName; var physicalPath = _env.ContentRootPath + "/Photos/" + filename; using (var stream = new FileStream(physicalPath, FileMode.Create)) { stream.CopyTo(stream); } return new JsonResult(filename); } catch (Exception) { return new JsonResult("anonymous.png"); } }You can refer to my code --> https://github.com/vyelve/.NETCoreWebAPICRUD
OR
[BindProperty] public IFormFile ImageFile { get; set; } public string Msg { get; set; } public static readonly List ImageExtensions = new() { ".JPG", ".BMP", ".PNG" }; //to restrict file extensions if (HttpContext.Request.Form.Files.Count > 0)// check if the user uploded something { ImageFile = HttpContext.Request.Form.Files.GetFile("file_Main"); if (ImageFile != null) { var extension = Path.GetExtension(ImageFile.FileName);//get file name if (ImageExtensions.Contains(extension.ToUpperInvariant())) { using var dataStream = new MemoryStream(); await ImageFile.CopyToAsync(dataStream); byte[] imageBytes = dataStream.ToArray(); // you can save this to your byte array variable and remove the 2 lines below string base64String = Convert.ToBase64String(imageBytes); User.UserPicture = base64String; // to save the image as base64String } else { Msg = "image format must be in JPG, BMP or PNG"; //Custom error message return Page(); } } } }Sachin SinghRank #66 · 26.2K reputationPosted Oct 9, 2022, 4:16 AM EDT
1. use below classes
public class Attachment { [Key] public int id { get; set; } [Column(TypeName = "nvarchar(50)")] public string FileName { set; get; } [Column(TypeName = "nvarchar(50)")] public string Description { set; get; } [Column(TypeName = "varbinary(MAX)")] public byte[] attachment { set; get; } } public class AttachmentViewModel { public string FileName { set; get; } public string Description { set; get; } public IFormFile attachment { set; get; } public List attachments { get; set; } }2. create following extension methods (use for professional projects)
public static string GetContenttype(string fileName) { var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider(); string contentType; if (!provider.TryGetContentType(fileName, out contentType)) { contentType = "application/octet-stream"; } return contentType; } public static string CreateUniqueFileExtension(string fileName) { fileName = Path.GetFileName(fileName); return Path.GetFileNameWithoutExtension(fileName) + "_" + Guid.NewGuid().ToString().Substring(0, 4) + Path.GetExtension(fileName); } public static byte[] GetByteArrayFromImage(IFormFile file) { using (var target = new MemoryStream()) { file.CopyTo(target); return target.ToArray(); } }3. use below code in your api method
var uniqueFileName = SPClass.CreateUniqueFileExtension(model.attachment.FileName); var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "attachment"); var filePath = Path.Combine(uploads, uniqueFileName); model.attachment.CopyTo(new FileStream(filePath, FileMode.Create)); //save the attachment to the database Attachment attachment = new Attachment(); attachment.FileName = uniqueFileName; attachment.Description = model.Description; attachment.attachment = SPClass.GetByteArrayFromImage(model.attachment); _appContext.attachments.Add(attachment); _appContext.SaveChanges(); //where model is viewModel as parameter of your api