以下のコードを使用してください:
Upload 関数を呼び出して、「xyz.png」、ファイル byte[]、サーバー URL などのパラメーターを渡すだけです。他のことは同じままです..応答関数で応答を取得します。私の場合、アップロードされたファイルの URL を受け取ります。それは私のために働いています。あなたも願っています。幸運を。
public void Upload(string name, byte[] content, String uriStr)
{
string boundary = Guid.NewGuid().ToString();
string header = "--" + boundary;
string footer = "--" + boundary + "--";
HttpWebRequest uploadRequest = (HttpWebRequest)WebRequest.Create(uriStr);
uploadRequest.ContentType = "multipart/form-data; boundary=" + boundary;
uploadRequest.Method = "POST";
StringBuilder headers = new StringBuilder();
headers.AppendLine(header);
headers.AppendLine("Content-Disposition: file; name=\"file\"; filename=\"" + name + "\"");
headers.AppendLine("Content-Type: application/octet-stream");
headers.AppendLine();
headers.AppendLine(Encoding.GetEncoding("iso-8859-1").GetString(content, 0, content.Length));
headers.AppendLine(footer);
Console.Write(headers.ToString());
byte[] contents = Encoding.GetEncoding("iso-8859-1").GetBytes(headers.ToString());
object[] data = new object[2] { uploadRequest, contents };
uploadRequest.BeginGetRequestStream(new AsyncCallback(GetData), data);
}
public void GetData(IAsyncResult result)
{
object[] data = (object[])result.AsyncState;
byte[] content = (byte[])data[1];
HttpWebRequest request = (HttpWebRequest)data[0];
Stream requestStream = request.EndGetRequestStream(result);
int start = 0, count = 1024;
while (true)
{
if (start + count > content.Length)
{
requestStream.Write(content, start, (content.Length - start));
break;
}
requestStream.Write(content, start, count);
start += count;
}
requestStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponse), request);
}
public void GetResponse(IAsyncResult result)
{
string imageUploadedUrl = "";
try
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string check = line.Substring(0, 9);
if (check == " <Url>")
{
imageUploadedUrl = line.Substring(9, (line.Length - 15));
break;
}
}
}
}
}