110,534
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 向服务器Post请求上传图片
/// </summary>
/// <param name="upload_url">请求地址 http://192.168.0.666:8080/aaa/uploadByPc.do </param>
/// <param name="id">项目索引</param>
/// <param name="images">原图byte[]</param>
/// <param name="thumbs">缩略图byte[]</param>
/// <param name="macCode">初次上传索引</param>
public static void HttpPost(string upload_url, long id, byte[] images, byte[] thumbs, long macCode)//Post请求
{
//构造post提交字段
string para = "";
if (macCode != 0)
{
para = string.Format("id={0}&images={1}&thumbs={2}", id, images, thumbs);
}
else
{
para = string.Format("id={0}&images={1}&thumbs={2}&macCode={3}", id, images, thumbs, macCode);
}
try
{
HttpWebRequest httpWeb = (HttpWebRequest)WebRequest.Create(upload_url);
byte[] bytePara = Encoding.UTF8.GetBytes(para);
httpWeb.Method = "POST";
httpWeb.Timeout = 30000;
httpWeb.ContentType = "application/x-www-form-urlencoded";
//application/x-www-form-urlencoded////multipart/form-data
httpWeb.ContentLength = bytePara.Length;
using (Stream reqStream = httpWeb.GetRequestStream())
{
//提交数据
reqStream.Write(bytePara, 0, para.Length);
}
////获取服务器返回值
//HttpWebResponse httpWebResponse = (HttpWebResponse)httpWeb.GetResponse();
//Stream stream = httpWebResponse.GetResponseStream();
//StreamReader streamReader = new StreamReader(stream, Encoding.Default);
////获得返回值
//string result = streamReader.ReadToEnd();
//stream.Close();
//将服务器返回值返回
//return result;
}catch(Exception ex){
//return ex.ToString();
}
private ByteArrayContent CreateFileContent(System.IO.MemoryStream stream, string fileName, string contentType)
{
var fileContent = new ByteArrayContent(stream.ToArray());
fileContent.Headers.Clear();
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"file\"",
FileName = "\"" + fileName + "\""
}; // the extra quotes are key here
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return fileContent;
}
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
//我这里接收的是stream,不过你传byte[],那就自己改一下
bm.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
HttpClient client = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(CreateFileContent(ms, msg.ToString() + ".jpg", "application/octet-stream"));
form.Add(“其他附属字段key”, '"' + "其他附属字段的value" + '"');
var result = client.PostAsync(url, form).Result.Content.ReadAsStringAsync().Result;
}
para = string.Format("id={0}&images={1}&thumbs={2}", id, images, thumbs);
这种东西,你稍微调试一下 para 变量的值,就知道有什么问题了。
看来你从来不调试。new WebClient().UploadFile(url, file);
就可以了。
你写那么多,何必呢?