文件保存
public string PostMember(byte[] imgBytes, string keyName = null, string fileName = null)
{
string URL = "https://openapi.baidu.com/file/2.0/b2b_tp/offline/upload/storeObject?access_token=24.92d553a75c05372448756cbe28d9cced.86400.1640226300.282335-25040229";
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
System.Net.WebRequest webRequest = System.Net.WebRequest.Create(URL);
webRequest.Method = "POST";
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
NameValueCollection formData = new NameValueCollection();
formData.Clear();
formData.Add("file_type","image");
//formData.Add("file", @"C:\Users\yc\Desktop\图片\注册公司内容027.jpg");
//formData["member_id"] = JsonConvert.SerializeObject(memberIds);
Stream postDataStream = new System.IO.MemoryStream();
string formDataHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +
"Content-Disposition: form-data; name=\"{0}\"" + Environment.NewLine + Environment.NewLine + "{1}";
foreach (string key in formData.Keys)
{
byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(formDataHeaderTemplate,
key, formData[key]));
postDataStream.Write(formItemBytes, 0, formItemBytes.Length);
}
//byte[] imgBytes = SaveImage(@"C:\Users\yc\Desktop\图片\注册公司内容027.jpg");
if (imgBytes != null)
{
string fileHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
Environment.NewLine + "Content-Type: {2}" + Environment.NewLine + Environment.NewLine;
byte[] fileHeaderBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(fileHeaderTemplate,
keyName, fileName, "image/png"));
postDataStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length);
postDataStream.Write(imgBytes, 0, imgBytes.Length);
}
byte[] endBoundaryBytes = System.Text.Encoding.UTF8.GetBytes(Environment.NewLine +
"--" + boundary + "--" + Environment.NewLine);
postDataStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
webRequest.ContentLength = postDataStream.Length;
Stream reqStream = webRequest.GetRequestStream();
postDataStream.Position = 0;
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = postDataStream.Read(buffer, 0, buffer.Length)) != 0)
{
reqStream.Write(buffer, 0, bytesRead);
}
postDataStream.Close();
reqStream.Close();
StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream());
string Result = sr.ReadToEnd();
return Result;
}
浙公网安备 33010602011771号