使用C#的MinimalAPI來實作檔案上傳和下載下傳,你可以按照以下步驟進行操作:
- 建立一個新的MinimalAPI項目:在終端中執行以下指令,建立一個新的MinimalAPI項目:
dotnet new web -n FileApi
這将建立一個名為"FileApi"的新的MinimalAPI項目。
- 添加必要的NuGet包:在終端中導航到"FileApi"項目的根目錄,然後運作以下指令,添加必要的NuGet包:
dotnet add package Microsoft.AspNetCore.StaticFiles
這将添加用于處理靜态檔案的包。
- 修改Program.cs檔案:打開"FileApi"項目的根目錄,找到"Program.cs"檔案,然後将其替換為以下代碼:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
var app = WebApplication.Create(args);
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(AppContext.BaseDirectory),
RequestPath = "/files"
});
app.Run();
// 實作檔案上傳和下載下傳的路由
app.MapPost("/upload", async (HttpContext context) =>
{
var form = await context.Request.ReadFormAsync();
var file = form.Files.FirstOrDefault();
if (file != null && file.Length > 0)
{
var filePath = Path.Combine(AppContext.BaseDirectory, file.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
context.Response.Redirect("/");
});
app.MapGet("/download/{fileName}", (HttpContext context) =>
{
var fileName = context.Request.RouteValues["fileName"]?.ToString();
if (!string.IsNullOrEmpty(fileName))
{
var filePath = Path.Combine(AppContext.BaseDirectory, fileName);
if (File.Exists(filePath))
{
return context.Response.SendFile(filePath);
}
}
context.Response.StatusCode = StatusCodes.Status404NotFound;
return context.Response.WriteAsync("File not found");
});
await app.RunAsync();
這段代碼會建立一個MinimalAPI應用程式,并添加處理靜态檔案的中間件。接着,我們定義了兩個路由用于處理檔案上傳和下載下傳。
- 運作應用程式:在終端中導航到"FileApi"項目的根目錄,然後運作以下指令,啟動應用程式:
dotnet run
應用程式将會在 http://localhost:5000 上運作。
現在,你可以使用任何HTTP用戶端(如Postman)來測試檔案上傳和下載下傳功能:
- 檔案上傳:發送一個POST請求到 http://localhost:5000/upload,并使用"multipart/form-data"格式将檔案上傳。
- 檔案下載下傳:發送一個GET請求到 http://localhost:5000/download/{fileName},其中{fileName}是你要下載下傳的檔案名。
這樣,你就可以使用C# MinimalAPI實作檔案上傳和下載下傳了。請記得在實際生産環境中,需要根據安全性和性能要求進行适當的配置和調整。
創作不易,如果您喜歡還請幫忙點贊關注,謝謝![作揖]