string PostData(HttpPostedFile postedFile, string url)
{
try
{
WebRequest req = WebRequest.Create(url);
req.Method = "POST";
String boundary = "---------------------------7d4a6d158c9"; // 分隔符
StringBuilder sb = new StringBuilder();
// 发送每个字段:
//sb = sb.Append("--");
//sb = sb.Append(boundary);
//sb = sb.Append("\r\n");
//sb = sb.Append("Content-Disposition: form-data; name=\"MailIDs\"\r\n\r\n");
//sb = sb.Append(Server.UrlEncode("1111111111"));
//sb = sb.Append("\r\n");
// 发送文件:
sb = sb.Append("--");
sb = sb.Append(boundary);
sb = sb.Append("\r\n");
sb = sb.Append("Content-Disposition: form-data; name=\"" + Server.UrlEncode(Path.GetFileNameWithoutExtension(postedFile.FileName))
+ "\"; filename=\"" + Server.UrlEncode(postedFile.FileName) + "\"\r\n");
sb = sb.Append("Content-Type: application/octet-stream\r\n\r\n");
byte[] data = Encoding.UTF8.GetBytes(sb.ToString());
byte[] end_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
req.ContentType = "multipart/form-data; boundary=" + boundary;
// Encode the data
byte[] encodedBytes = new byte[postedFile.InputStream.Length];
req.ContentLength = data.Length + encodedBytes.Length + end_data.Length;
postedFile.InputStream.Read(encodedBytes, 0, encodedBytes.Length);
// Write encoded data into request stream
using (Stream requestStream = req.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
requestStream.Write(encodedBytes, 0, encodedBytes.Length);
requestStream.Write(end_data, 0, end_data.Length);
requestStream.Close();
using (WebResponse res = req.GetResponse())
{
using (Stream receiveStream = res.GetResponseStream())
{
StreamReader sr = new StreamReader(receiveStream);
return sr.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
ErrorLog.WriteErrorLog("URL:" + url + ex.ToString());
return "";
}
}
发送文件
最新推荐文章于 2021-08-30 16:31:43 发布