Loading

Loading

C#使用HttpClient上传文件至阿里云oss失败的解决方案。

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();
posted @ 2024-06-03 10:30  热情定无变  阅读(514)  评论(0)    收藏  举报