ASP.NET Core 2.1文件上传DirectoryNotFoundException:找不到路径的一部分

时间:2018-11-10 07:13:27

标签: c# asp.net asp.net-core

这是我上传文件时的控制器代码。由于某些原因,我一直收到此错误:

  

DirectoryNotFoundException:找不到路径的一部分

[ValidateAntiForgeryToken]
[HttpPost]
public async Task<ActionResult> Save(UploadDocumentViewModel Input)
{
    var filePath = $"{this.hostingEnvironment.WebRootPath}/documents";
    foreach(var item in Request.Form.Files)
    {
        var fileName = ContentDispositionHeaderValue.Parse(item.ContentDisposition).FileName;
        fileName = fileName.Trim('"');
        var fullFilePath = Path.Combine(filePath, fileName);
        using(var stream = new FileStream(fullFilePath, FileMode.Create))
        {
            await item.CopyToAsync(stream);
        }
    }
    return this.Ok();
}

这是我要上传到的目录:

  

'C:\ Users \ uuu \ Source \ Repos \ Applicat \ Applicatto \ wwwroot \ documents \ 2018-10-27.png'。

据我了解,它的说法是找不到路径?但是我手动创建了documents文件夹,仍然会发生此错误。

编辑:

控制器顶部:

private readonly ILogger<DocumentsController> logger;
private readonly IHostingEnvironment hostingEnvironment;

public DocumentsController(ILogger<DocumentsController> logger, IHostingEnvironment hostingEnvironment)
{
    this.logger = logger;
    this.hostingEnvironment = hostingEnvironment;
}

1 个答案:

答案 0 :(得分:1)

我认为问题出在物理路径上。

这是我通常使用的正常方式(我删除了记录器是因为在本示例中不使用它-只是为了使代码更短,但是您可以定义并再次使用它):

public class DocumentsController : Controller
{
    // you should name the field(s) like this to make it/them difference
    private readonly IHostingEnvironment _hostingEnvironment;

    public DocumentsController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    [ValidateAntiForgeryToken]
    [HttpPost]
    public async Task<ActionResult> Save(UploadDocumentViewModel Input)
    {
        // NOTE: we don't need "/" character before the path, like "/documents"
        string filePath = Path.Combine(_hostingEnvironment.WebRootPath, "documents");

        // then, copy and paste your code to continue
    }
}

注意::由于我们使用ASP.NET Core,因此我们希望返回IActionResult而不是ActionResult