Asp.Net Core 3.1 MVC Bagaimana cara mengupload foto dalam proyek? [duplikat]

Dec 07 2020

Asp.Net Core 3.1 MVC Dalam proyek saya , pengguna perlu mengunggah foto dan saya ingin menyimpan foto di bawah wwwroot / database. Dalam database, hanya jalur ke foto yang diperlukan, tetapi setiap kali objek IFromfile saya menjadi null. Terima kasih mulai sekarang

Jawaban

Yinqiu Dec 07 2020 at 16:21

Anda dapat melakukannya dengan langkah-langkah berikut.

  1. Buat model Image:

    public class Image
    {
        public int Id { get; set; }
        public string Path { get; set; } 
    }
    
  2. Buat folder di Imagesbawah Andawwwroot

  3. Kode tampilan indeks:

    @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. Pengontrol:

    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();
        }
    

Hasil: