我正在处理一个第三方API,该API坚持将二进制文件上传请求格式化为而没有设置Content-Type
头值为multipart/form-data
,并且具有以下头:
Content-Type: application/octet-stream
Content-Disposition: filename*=UTF-8''file.zip
HttpRequestMessage
和HttpContent.Headers.ContentDisposition.DispositionType
不允许我实现此目的,因为我无法根据需要设置值,或者它们会自动设置它们。
我接受此API可能未遵循HTTP标准,但它不是我的,因此对它没有影响。
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.ExpectContinue = false;
FileStream fs = new FileStream(@"e:\dev\TestHalfB.docx", FileMode.Open);
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, <Uri>);
HttpContent fc = new StreamContent(fs);
var mpContent = new MultipartFormDataContent();
mpContent.Add(fc);
fc.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
req.Content = fc;
fc.Headers.ContentDisposition.DispositionType = "filename*=UTF-8''TestHalfB.docx";
using (var response = await client.SendAsync(req))
{
response.EnsureSuccessStatusCode();
var resp = await response.Content.ReadAsStringAsync();
}
fs.Close();
}
有人知道我可以使用较低级别的API或有任何建议吗?
关键是如何将Content-Disposition
标头设置为所需的值。
答案 0 :(得分:0)
可以请您尝试一下。
HttpContent fileStreamContent = new StreamContent(paramFileStream);
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileStreamContent, "file1", "file1");
var response = client.PostAsync(actionUrl, formData).Result;
}
答案 1 :(得分:0)
我不得不改用WebRequest
。
WebRequest request = WebRequest.Create("https://cloud.memsource.com/web/api2/v1/projects/{id}/jobs?token={token}");
request.Method = "POST";
byte[] byteArray = File.ReadAllBytes(@"E:\Dev\TestHalfB.docx");
request.ContentType = "application/octet-stream";
request.ContentLength = byteArray.Length;
request.Headers.Add("Content-Disposition", "filename*=UTF-8''TestHalfB.docx");
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
((HttpWebResponse)response).StatusDescription.Dump();
答案 2 :(得分:-1)
这应该对您有用(或者至少让您入门,因为它未经测试):
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, <Uri>);
using (FileStream fs = new FileStream(@"e:\dev\TestHalfB.docx", FileMode.Open))
{
byte[] fb = new byte[(int)fs.Length]; // assumes your file size will fit into an int
await fs.ReadAsync(fb, 0, (int)fs.Length);
req.Content = new ByteArrayContent(fb);
req.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
req.Content.Headers.ContentDisposition.FileNameStar = "UTF-8''TestHalfB.docx";
using (var response = await client.SendAsync(req))
{
response.EnsureSuccessStatusCode();
var resp = await response.Content.ReadAsStringAsync();
}
}