我正在尝试从C#创建一个分段上传请求,以便根据https://developers.google.com/drive/v3/web/multipart-upload将小文件上传到Google云端硬盘
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token);
//api endpoint
var apiUri = new Uri("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart");
// read the image content
var imageBinaryContent = new ByteArrayContent(fileBytes);
imageBinaryContent.Headers.Add("Content-Type", "image/jpeg");
// prepare the metadata content
string metaContent = "{\"name\":\"myObject\"}";
byte[] byteArray = Encoding.UTF8.GetBytes(metaContent);
var metaStream = new ByteArrayContent(byteArray);
metaStream.Headers.Add("Content-Type", "application/json; charset=UTF-8");
// create the multipartformdata content, set the headers, and add the above content
var multipartContent = new MultipartFormDataContent();
multipartContent.Headers.Remove("Content-Type");
multipartContent.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundry=myboundry---");
multipartContent.Add(metaStream);
multipartContent.Add(imageBinaryContent);
HttpResponseMessage result = await client.PostAsync(apiUri, multipartContent);
}
但我似乎无法让它发挥作用。此代码适用于简单上传到云端硬盘:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token);
//api endpoint
var apiUri = new Uri("https://www.googleapis.com/upload/drive/v3/files?uploadType=media");
// read the image content
var imageBinaryContent = new ByteArrayContent(fileBytes);
imageBinaryContent.Headers.Add("Content-Type", "image/jpeg");
HttpResponseMessage result = await client.PostAsync(apiUri, imageBinaryContent);
}
答案 0 :(得分:0)
有两件事情跳出来:
boundary
中拼错了boundry=myboundry
这个词。 Content-Type
为multipart/related
。答案 1 :(得分:0)
对于那些尝试在.net内核中进行尝试的人来说,这是我的代码:
public async Task UploadFile(Stream stream, string filename)
{
var accessToken = "";
using var client = _httpClientFactory.CreateClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var metaContent = JsonContent.Create(new { name = filename });
var streamContent = new StreamContent(stream);
var multipart = new MultipartContent { metaContent, streamContent };
streamContent.Headers.ContentType = new MediaTypeHeaderValue(MediaTypeNames.Application.Octet);
streamContent.Headers.ContentLength = stream.Length;
var result = await client.PostAsync("https://www.googleapis.com/upload/drive/v3/files?uploadtype=multipart", multipart);
}