天天看點

在ASP.NET Core 中上傳檔案

目錄

簡介

傳檔案的作用

代碼實作

簡介

ASP.NET Core 支援使用緩沖的模型綁定(針對較小檔案)和無緩沖的流式傳輸(針對較大檔案)上傳一個或多個檔案。

傳檔案的作用

1.上傳是支援上傳任何檔案的,圖檔隻是上傳的一種。

2.根據擴充名進行區分你所上傳的檔案形式。

代碼實作

1、安裝 Microsoft.AspNetCore.StaticFiles 包

Install-Package Microsoft.AspNetCore.StaticFiles
           

2、在 Startup.cs 中的 ConfigureServices 方法中添加以下代碼

services.AddDirectoryBrowser();
           

3、在 Startup.cs 中的 Configure 方法中添加以下代碼

app.UseStaticFiles();
app.UseFileServer(new FileServerOptions()
 {
    FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\uploads")),
    RequestPath = new PathString("/Uploads"),
    EnableDirectoryBrowsing = true
 });
           

4、在 wwwroot 目錄下建立一個名為 uploads 的檔案夾,用來存放上傳檔案

5、在項目中添加一個上傳檔案的表單,如下:

<form action="/Home/UploadFile" enctype="multipart/form-data" method="post">
    <input type="file" name="file" />
    <input type="submit" value="上傳" />
</form>
           

6、在 HomeController 中添加一個上傳檔案的 Action 方法,如下:

[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
    if (file == null || file.Length == 0)
        return Content("檔案不能為空");

    var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", file.FileName);

    using (var stream = new FileStream(path, FileMode.Create))
    {
        await file.CopyToAsync(stream);
    }

    return RedirectToAction("Index");
}
           

7、在浏覽器中輸入 http://localhost:port/uploads,就可以看到上傳的檔案

繼續閱讀