【问题标题】:Asp.Net Core 3.1 MVC How to upload photos in the project? [duplicate]Asp.Net Core 3.1 MVC 项目中如何上传照片? [复制]
【发布时间】:2020-12-07 08:33:01
【问题描述】:

Asp.Net Core 3.1 MVC 在我的项目中,用户需要上传一张照片,我想把照片保存在 wwwroot/database 下。在数据库中,只需要照片的路径,但每次我的 IFromfile 对象都为空。从现在开始谢谢你

【问题讨论】:

    标签: c# asp.net-mvc-3 razor asp.net-core-mvc


    【解决方案1】:

    您可以通过以下步骤来做到这一点。

    1. 创建模型Image

      public class Image
      {
          public int Id { get; set; }
          public string Path { get; set; } 
      }
      
    2. 在您的wwwroot 下创建一个文件夹Images

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

    结果:

    【讨论】:

    • 您无需等待CopToAsync(),而是让用户使用上传中提供的文件名覆盖彼此的文件,而不是生成一个服务器端。此外,OP 的问题是 “IFromfile 对象为 null”,所以问题出在他们的客户端代码上,没有显示。
    • 我不知道谁同情这个答案,但它是从stackoverflow.com/a/63822872 复制的,包括fileSrteam 错字和非唯一文件名问题,并通过删除await 变得更糟。
    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 2020-07-19
    • 2020-07-29
    • 2021-04-27
    相关资源
    最近更新 更多