-1

Asp.Net Core 3.1 MVC In my project, the user needs to upload a photo and I want to keep the photo under wwwroot / database. In the database, only the path to the photo is required, but every time my IFromfile object comes as null. Thank you from now

talha
  • 43
  • 4

1 Answers1

0

You can do it with the following steps.

  1. Create a model Image:

    public class Image
    {
        public int Id { get; set; }
        public string Path { get; set; } 
    }
    
  2. Create a folder Images under your wwwroot

  3. The index view code:

    @model Image
    
    <form asp-controller="Home" asp-action="Index" method="post" enctype="multipart/form-data">
        <input type="file" name="uploadFile" class="form-control" />
        <input type="submit" value="submit" id="sub" />
    </form>
    
  4. Controller:

    public class HomeController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly IWebHostEnvironment _hostingEnvironment;
    
        public HomeController(ApplicationDbContext context, IWebHostEnvironment hostingEnvironment)
        {
            _context = context;
            _hostingEnvironment = hostingEnvironment;
        }
    
        public IActionResult Index()
        {
            return View();
        }
    
        [HttpPost]
        public async Task<IActionResult> IndexAsync(Image image,IFormFile uploadFile)
        {
            if (uploadFile != null && uploadFile.Length > 0)
            {
                var fileName = Path.GetFileName(uploadFile.FileName);
                var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", fileName);
                image.Path = filePath;
    
                _context.Images.Add(image);
                _context.SaveChanges();
    
                using (var fileSrteam = new FileStream(filePath, FileMode.Create))
                {
                     await uploadFile.CopyToAsync(fileSrteam);
                }
            }
    
            return View();
        }
    

Results:

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Yinqiu
  • 6,609
  • 1
  • 6
  • 14
  • You don't await `CopToAsync()`, and you let users overwrite each other's files by using the provided filename from the upload, instead of generating one serverside. Also, the OP's problem is _"IFromfile object comes as null"_, so the problem is with their client code, which isn't show. – CodeCaster Dec 07 '20 at 09:35
  • I don't know who pity-upvoted this answer, but it is copied from https://stackoverflow.com/a/63822872/, including `fileSrteam` typo and non-unique filename issue, and made worse by removing `await`. – CodeCaster Dec 07 '20 at 09:40