请使用以下代码:
只需调用 Upload 函数并传递参数,如“xyz.png”、文件字节 []、您的服务器 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;
}
}
}
}
}