Asp.Net Core 3.1 MVCプロジェクトに写真をアップロードする方法は?[複製]

Dec 07 2020

Asp.Net Core 3.1 MVC私のプロジェクトでは、ユーザーが写真をアップロードする必要があり、その写真をwwwroot / databaseに保存したいと考えています。データベースでは、写真へのパスのみが必要ですが、IFromfileオブジェクトがnullになるたびに。今からありがとう

回答

Yinqiu Dec 07 2020 at 16:21

次の手順で実行できます。

  1. モデルを作成しますImage

    public class Image
    {
        public int Id { get; set; }
        public string Path { get; set; } 
    }
    
  2. Images下にフォルダを作成しますwwwroot

  3. インデックスビューコード:

    @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. コントローラ:

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

結果: