我正在上传图片。
我想设置Content-Type =“ multipart / form-data; boundary = ---- WebKitFormBoundaryFoxUxCRayQhs5eNN”的值
使用代码:
HttpRequestMessage request=new HttpRequestMessage();
request.Content.Headers.ContentType="multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN";
或request.Header.ContentType="multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN";
这将导致错误:所标识的项之一格式无效。
如果仅设置“ multipart / form-data”,则可以,但是无法上传文件。
如何设置?
答案 0 :(得分:1)
以下是一些代码片段,您可以参考:
using (var client = new HttpClient())
using (var fileStream = File.Open(fileName, FileMode.Open, FileAccess.Read)
using (var streamContent = new StreamContent(fileStream))
{
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
streamContent.Headers.ContentDisposition.Name = "\"file\"";
streamContent.Headers.ContentDisposition.FileName = "\"" + fileName + "\"";
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
string boundary = "WebKitFormBoundaryFoxUxCRayQhs5eNN";
var fContent = new MultipartFormDataContent(boundary);
fContent.Headers.Remove("Content-Type");
fContent.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
fContent.Add(streamContent);
var response = await client.PostAsync(new Uri(url), fContent);
response.EnsureSuccessStatusCode();
}
如果您使用HttpWebRequest,则可以参考以下内容:https://stackoverflow.com/a/20000831/10768653