Refit 使用紀錄II - 下載上傳檔案

Refit, HttpClient 應用簡化方案之一。WASM, Blazor WebAssembly 下載檔案、上傳檔案。

開發環境

平台:.NET6

骨架:Blazor WASM App

IDE:Visual Studio 2022

關鍵原碼紀錄-下載檔案-Client

_FileLab.razor
@using System.Net
@page "/file"
@attribute [Authorize]
@inject IFileHandleApi bizApi
@inject JSInterOpService jsTool

  <MudToolBar Class="gap-3">
    <MudButton Variant=Variant.Filled Color=Color.Primary OnClick=HandleDonloadFile>測試下載檔案</MudButton>
    <MudCheckBox @bind-Checked=f_testFail Color=Color.Warning>測試邏輯失敗</MudCheckBox>
  </MudToolBar>

[...略...]

@code {
  //## State
  string errMsg = string.Empty;
  bool f_loading = false;
  string message = string.Empty;
  bool f_testFail = false;

  async Task HandleDonloadFile()
  {
    // 模擬下載失敗狀況
    Guid id = f_testFail ? Guid.Empty : Guid.NewGuid();
    
    HttpContent content = await bizApi.DowloadFileAsync(id);
    byte[] fileBlob = await content.ReadAsByteArrayAsync();

    // 取得檔名
    string filenameU = content.Headers.GetValues("Content-Disposition").First().Split("filename*=UTF-8''")[1];
    string filename = Uri.UnescapeDataString(filenameU); // 解碼

    await jsTool.DownloadFileAsync(filename, fileBlob);
  }
}

關鍵原碼紀錄-上傳檔案-Client

上傳檔案用 FormDataarrow-up-right 封包處理。在 ASP.NET 名為 MultipartFormDataContentarrow-up-right

若用 HttpClient 上傳檔案,語法如下:

定義下載上傳 Refit Client 介面

關鍵原碼紀錄 - Server side

完整原始碼

參考

Refit 使用紀錄chevron-right

下載

上傳

Last updated