【问题标题】:How to Upload a file in Dotnet core 3.1 Web app如何在 Dotnet core 3.1 Web 应用程序中上传文件
【发布时间】:2020-07-09 22:19:27
【问题描述】:

实际上我正在尝试从用户上传文件。但我遇到了错误。我也尝试了各种方式,甚至是 Microsoft doc。我无法自拔。所以请帮帮我

链接:Microsoft Doc dotnet core 3.1

我的行动:

[HttpPost]
        public async Task<IActionResult> Updateperson(UpdatePersonViewModel updatePerson)
        {
           if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if(updatePerson.Photo != null)
                {
                    string[] words = updatePerson.Photo.FileName.Split('.');
                    int a = words.Rank;
                    uniqueFileName = words[a];
                    uniqueFileName = Guid.NewGuid().ToString() + "_." + uniqueFileName;
                    string filePath = Path.Combine("Images",uniqueFileName);

                    //string filePath = Path.Combine(config["Images"], uniqueFileName);
                    //  using (var stream = System.IO.File.Create(filePath))
                    //        {
                    //           await formFile.CopyToAsync(stream);
                    //           }

                    await updatePerson.Photo.CopyToAsync(new FileStream(filePath,FileMode.Create));
                }
                _context.Persons.Update(updatePerson);
                _context.SaveChanges();
                return RedirectToAction("Profile", new RouteValueDictionary(new { action = "Profile", id = updatePerson.Id }));
            }
            else
            {
                return RedirectToAction("Profile", new RouteValueDictionary(new { action = "Profile", id = updatePerson.Id }));
            }


        }

>>> config 是 IConfiguration 的一个对象

这是错误:

【问题讨论】:

    标签: c# model-view-controller .net-core web-applications asp.net-core-3.1


    【解决方案1】:

    表示不存在名为Image的目录!

    您可以简单地检查它是否存在,或者如果它不存在则创建一个。

    if(!Directory.Exists(directoryPath))
    {
    Directory.CreateDirectory(directoryPath);
    }
    

    测试:

    像这样使用directoryPath 变量:

    var directoryPath=Path.Combine(Directory.GetCurrentDirectory(), "Images");
    

    【讨论】:

    • 可能是目录路径错误。我还是编辑了我的答案。
    • 在我的 wwwroot 文件夹中,我创建了 Images 文件夹。我找不到实际路径
    • 您不应该将图像放在 wwwroot 中。这意味着您每次都将为用户下载数据库中的所有内容。只需删除文件夹并测试代码即可。
    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    相关资源
    最近更新 更多