C#使用HttpClient上傳檔案至阿里雲oss失敗的解決方案。

热情定无变發表於2024-06-03

The body of your POST request is not well-formed multipart/form-data在使用C#的HttpClient上傳檔案到阿里雲oss的時候,根據postman生成的程式碼,但是用C#發起請求的時候會返回400錯誤以及錯誤資訊 > The body of your POST request is not well-formed multipart/form-data

主要因為以下幾個原因:

1. 在Http Header中Content-Type中,boundary需要不帶雙引號

2. 在Form中,每個Form的name值需要用雙引號引起來

3. 如果檔案表單域帶有Content-TypeHeader,則該欄位需要放在Content-Disposition欄位後

4. 檔案表單域在Content-Disposition中需要帶有fileName

5. 檔案表單域Content-Disposition不支援filename*=utf-8''%22a.txt%22這樣的檔名錶示

以下是解決後的程式碼

檢視程式碼

var fileName = $"{storageData.Key}{Path.GetExtension(filePath)}";
var streamContent = new StreamContent(File.OpenRead(filePath));
var multipartForm = new MultipartFormDataContent($"-----{Guid.NewGuid()}")
{
    { new ByteArrayContent(Encoding.UTF8.GetBytes(storageData.AccessId)), "\"OSSAccessKeyId\"" },
    { new ByteArrayContent(Encoding.UTF8.GetBytes(fileName)), "\"Key\"" },
    { new ByteArrayContent(Encoding.UTF8.GetBytes(storageData.Policy)), "\"Policy\"" },
    { new ByteArrayContent(Encoding.UTF8.GetBytes("200")), "\"Success_action_status\"" },
    { new ByteArrayContent(Encoding.UTF8.GetBytes(storageData.Signature)), "\"Signature\"" },
    { streamContent, "\"file\"", $"\"{Path.GetFileName(filePath)}\"" }
};
var boundary = multipartForm.Headers.ContentType.Parameters.First(o => o.Name == "boundary");
boundary.Value = boundary.Value.Replace("\"", string.Empty);
streamContent.Headers.ContentDisposition.FileNameStar = null;
var httpResponse = await HttpClient.PostAsync(url, multipartForm);
httpResponse.EnsureSuccessStatusCode();

相關文章