gpt4 book ai didi

c# - 如何从 C# 提交 multipart/form-data HTTP POST 请求

转载 作者:可可西里 更新时间:2023-11-01 07:46:50 28 4
gpt4 key购买 nike

从 C# 提交带有 multipart/form-data 内容类型的 HTTP POST 请求的最简单方法是什么?必须有比构建我自己的请求更好的方法。

我问的原因是使用此 api 将照片上传到 Flickr:

http://www.flickr.com/services/api/upload.api.html

最佳答案

如果您使用的是 .NET 4.5,请使用:

public string Upload(string url, NameValueCollection requestParameters, MemoryStream file)
{

var client = new HttpClient();
var content = new MultipartFormDataContent();

content.Add(new StreamContent(file));
System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string, string>> b = new List<KeyValuePair<string, string>>();
b.Add(requestParameters);
var addMe = new FormUrlEncodedContent(b);

content.Add(addMe);
var result = client.PostAsync(url, content);
return result.Result.ToString();
}

否则根据 Ryan 的回答,我下载了库并稍微调整了一下。

  public class MimePart
{
NameValueCollection _headers = new NameValueCollection();
byte[] _header;

public NameValueCollection Headers
{
get { return _headers; }
}

public byte[] Header
{
get { return _header; }
}

public long GenerateHeaderFooterData(string boundary)
{
StringBuilder sb = new StringBuilder();

sb.Append("--");
sb.Append(boundary);
sb.AppendLine();
foreach (string key in _headers.AllKeys)
{
sb.Append(key);
sb.Append(": ");
sb.AppendLine(_headers[key]);
}
sb.AppendLine();

_header = Encoding.UTF8.GetBytes(sb.ToString());

return _header.Length + Data.Length + 2;
}

public Stream Data { get; set; }
}

public string Upload(string url, NameValueCollection requestParameters, params MemoryStream[] files)
{
using (WebClient req = new WebClient())
{
List<MimePart> mimeParts = new List<MimePart>();

try
{
foreach (string key in requestParameters.AllKeys)
{
MimePart part = new MimePart();

part.Headers["Content-Disposition"] = "form-data; name=\"" + key + "\"";
part.Data = new MemoryStream(Encoding.UTF8.GetBytes(requestParameters[key]));

mimeParts.Add(part);
}

int nameIndex = 0;

foreach (MemoryStream file in files)
{
MimePart part = new MimePart();
string fieldName = "file" + nameIndex++;

part.Headers["Content-Disposition"] = "form-data; name=\"" + fieldName + "\"; filename=\"" + fieldName + "\"";
part.Headers["Content-Type"] = "application/octet-stream";

part.Data = file;

mimeParts.Add(part);
}

string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
req.Headers.Add(HttpRequestHeader.ContentType, "multipart/form-data; boundary=" + boundary);

long contentLength = 0;

byte[] _footer = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");

foreach (MimePart part in mimeParts)
{
contentLength += part.GenerateHeaderFooterData(boundary);
}

//req.ContentLength = contentLength + _footer.Length;

byte[] buffer = new byte[8192];
byte[] afterFile = Encoding.UTF8.GetBytes("\r\n");
int read;

using (MemoryStream s = new MemoryStream())
{
foreach (MimePart part in mimeParts)
{
s.Write(part.Header, 0, part.Header.Length);

while ((read = part.Data.Read(buffer, 0, buffer.Length)) > 0)
s.Write(buffer, 0, read);

part.Data.Dispose();

s.Write(afterFile, 0, afterFile.Length);
}

s.Write(_footer, 0, _footer.Length);
byte[] responseBytes = req.UploadData(url, s.ToArray());
string responseString = Encoding.UTF8.GetString(responseBytes);
return responseString;
}
}
catch
{
foreach (MimePart part in mimeParts)
if (part.Data != null)
part.Data.Dispose();

throw;
}
}
}

关于c# - 如何从 C# 提交 multipart/form-data HTTP POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1203811/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com