Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

How to write multiple files to the database?

$
0
0
public class Image
    {
        [Key]
        public int ImageId { get; set; }

        public string ImageFile { get; set; }
    }
[Route("Images/Create")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("ImageId,ImageFile")] Image image, IEnumerable<IFormFile> files)
        {
            if (ModelState.IsValid)
            {
                string fileExtension;
                string fileName;
                string dateTimeNow;
                string newFileName;

                foreach (var file in files)
                {
                    if (file != null && file.Length > 0)
                    {
                        fileExtension = System.IO.Path.GetExtension(file.FileName);
                        fileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName);
                        dateTimeNow = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
                        newFileName = fileName + "_" + dateTimeNow + fileExtension;

                        image.ImageFile = newFileName;

                        var uploads = Path.Combine(_env.WebRootPath, "UploadedPageImages");
                        if (file.Length > 0)
                        {
                            var filePath = Path.Combine(uploads, newFileName);
                            using (var fileStream = new FileStream(filePath, FileMode.Create))
                            {
                                await file.CopyToAsync(fileStream);
                            }
                        }
                    }

                    _context.Add(image);
                    await _context.SaveChangesAsync();
                }

                return RedirectToAction(nameof(Index));
            }
            return View(image);
        }

And I got this error:

SqlException: Cannot insert explicit value for identity column in table 'Image' when IDENTITY_INSERT is set to OFF.


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>