private static void GetRequestStreamCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; string path = errorPathList[0]; int pos = path.LastIndexOf("\\"); string fileName = path.Substring(pos + 1); ////请求头部信息 FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); byte[] bArr = new byte[fs.Length]; fs.Read(bArr, 0, bArr.Length); fs.Close(); Stream postStream = request.EndGetRequestStream(asynchronousResult); MsMultiPartFormData form = new MsMultiPartFormData(postStream); //form.AddFormField("token", "UmyhgwyTCXazlqnBh6sypTbxuCrH0VUQ8vjNoPzT:lf4Kcq7RrRrg508o25YxdusZyTU=:eyJzY29wZSI6InRzdGRkdW1wIiwiZGVhZGxpbmUiOjE0NTQzNTMyNTZ9"); form.AddFormField("token", "UmyhgwyTCXazlqnBh6sypTbxuCrH0VUQ8vjNoPzT:nMp6tOdlV9jz4fsGvju-Kv2vvik=:eyJzY29wZSI6InRzdGRkdW1wIiwiZGVhZGxpbmUiOjE3NzExNDY5NjN9"); form.AddFormField("key", path); form.AddStreamFile("file", fileName, bArr); form.PrepareFormData(); postStream.Close(); request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request); }
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; string path = errorPathList[0]; int pos = path.LastIndexOf("\\"); string fileName = path.Substring(pos + 1); ////请求头部信息 FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); byte[] bArr = new byte[fs.Length]; fs.Read(bArr, 0, bArr.Length); fs.Close(); Stream postStream = request.EndGetRequestStream(asynchronousResult); MsMultiPartFormData form = new MsMultiPartFormData(postStream); //form.AddFormField("token", "UmyhgwyTCXazlqnBh6sypTbxuCrH0VUQ8vjNoPzT:lf4Kcq7RrRrg508o25YxdusZyTU=:eyJzY29wZSI6InRzdGRkdW1wIiwiZGVhZGxpbmUiOjE0NTQzNTMyNTZ9"); form.AddFormField("token", "UmyhgwyTCXazlqnBh6sypTbxuCrH0VUQ8vjNoPzT:EHu4cZi6Dbky2bAfgHLupWTmcx4=:eyJzY29wZSI6InRzdGRkdW1wIiwiY2FsbGJhY2tVcmwiOiJodHRwOi8vY3Jhc2gueHkzZC5tb2JpL3VwbG9hZC90c3RkX2NsaWVudCIsImNhbGxiYWNrQm9keSI6ImtleT0kKGtleSkiLCJkZWFkbGluZSI6MTgyMjUyNjc0Mn0="); form.AddFormField("key", "tstd_error_" + fileName); form.AddStreamFile("file", fileName, bArr); form.PrepareFormData(); postStream.Close(); request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request); }
public void UploadFile() { var api = Tools.GetSetting("上传模型"); if (api == null) { return; } try { var path = Path.Combine(TempPath, modelName + ".svfzip"); var client = new RestClient(api); var form = new MsMultiPartFormData(); form.AddFormField("token", token); var response = Tools.HttpPostData("http://192.168.2.132/api/upload/model/svfzip", form, path); var obj = JsonConvert.DeserializeObject(response) as JObject; if ((int)obj["status"] == 1) { //File.Delete(TempPath + modelName + ".svfzip"); progressBar1.Value = 100; if (SetType == 1) { var obj_add = _AddModel(token, obj["objectKey"].ToString(), option_id, modelName, pid); Tools.ShowMessageBox(obj_add["msg"].ToString()); } else if (SetType == 2) { var obj_re = _ReModel(token, obj["objectKey"].ToString(), option_id, modelName, pid, id); Tools.ShowMessageBox(obj_re["msg"].ToString()); } SetType = 0; Enabled = true; } else { Tools.ShowMessageBox(obj["msg"].ToString()); } } catch (Exception e) { Tools.ShowMessageBox(e.Message); } }
/// <summary> /// 上传图片或文件 不能大于2M /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static string Upfile(string filePath) { FileStream file = new FileStream(filePath, FileMode.Open); byte[] bb = new byte[file.Length]; file.Read(bb, 0, (int)file.Length); file.Close(); string fileName = Path.GetFileName(filePath); MsMultiPartFormData form = new MsMultiPartFormData(); string decodeName = HttpUtility.UrlDecode(Path.GetFileName(fileName));//最终服务器会按原文件名保存文件,所以需要将文件名编码下,防止中文乱码 string fileKeyName = "media"; form.AddStreamFile(fileKeyName, fileName, bb); String hashMd5 = Lib.HashHelper.ComputeMD5(filePath); WxPayData inputObj = new WxPayData(); inputObj.SetValue("mch_id", WxPayConfig.GetConfig().GetMchID()); inputObj.SetValue("media_hash", hashMd5); inputObj.SetValue("sign_type", "HMAC-SHA256"); //inputObj.SetValue("sign", inputObj.MakeSign());//签名 form.AddFormField("mch_id", WxPayConfig.GetConfig().GetMchID()); form.AddFormField("media_hash", hashMd5); form.AddFormField("sign_type", "HMAC-SHA256"); form.AddFormField("sign", inputObj.MakeSign()); //签名 string SERVICE_URL = "https://api.mch.weixin.qq.com/secapi/mch/uploadmedia"; //最终接收文件上传的服务接口 string rst = Lib.HttpService.Post(inputObj.ToXml(), SERVICE_URL, form, true, 10); inputObj = new WxPayData(); inputObj.FromXml(rst); if (inputObj.GetValue("return_code").ToString() == "SUCCESS") { return(inputObj.GetValue("media_id").ToString()); } return(inputObj.GetValue("return_msg").ToString()); }
public object UploadPic(FileData[] fds) { try { WebRequest request = (HttpWebRequest)WebRequest.Create(ServiceURL + "uploadAdver"); MsMultiPartFormData form = new MsMultiPartFormData(); form.AddFormField("devilField", "中国人"); form.AddStreamFile("fileUpload", fds[0].FileName, fds[0].FileBytes); form.PrepareFormData(); request.ContentType = "multipart/form-data; boundary=" + form.Boundary; request.Method = "POST"; Stream stream = request.GetRequestStream(); foreach (var b in form.GetFormData()) { stream.WriteByte(b); } stream.Close(); string responseContent = ""; using (HttpWebResponse res = (HttpWebResponse)request.GetResponse()) { using (Stream resStream = res.GetResponseStream()) { byte[] buffer = new byte[1024]; int read; while ((read = resStream.Read(buffer, 0, buffer.Length)) > 0) { responseContent += Encoding.UTF8.GetString(buffer, 0, read); } } res.Close(); } JavaScriptSerializer js = new JavaScriptSerializer(); List <FJ> list = js.Deserialize <List <FJ> >(responseContent); return(list); } catch (Exception ex) { throw ex; } }
string UPLOADFILE_SERVICE_URL = "http://.....";//最终接收文件上传的服务接口 public ActionResult RequestSave1(HttpContext context) { string temSavePath = context.Server.MapPath(@"~\") + RootFolder; if (!Directory.Exists(temSavePath)) { Directory.CreateDirectory(temSavePath); } if (context.Request.Files != null && context.Request.Files.Count > 0) { HttpPostedFile file = context.Request.Files[0]; string saveFileName = String.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddhhmmssffff"), Path.GetExtension(file.FileName));//保存文件名称 string fileName = String.Format(@"{0}\{1}", temSavePath, saveFileName); file.SaveAs(fileName); MsMultiPartFormData form = new MsMultiPartFormData(); string decodeName = HttpUtility.UrlDecode(Path.GetFileName(fileName)); //最终服务器会按原文件名保存文件,所以需要将文件名编码下,防止中文乱码 string rst = PostDataServer.HttpPostData(UPLOADFILE_SERVICE_URL, form, fileName, decodeName); context.Response.Write(rst); //输出上传文件返回结果 context.Response.End(); } return(null); }
/// <summary> /// 上传文件 /// </summary> /// <param name="xml"></param> /// <param name="url"></param> /// <param name="form"></param> /// <param name="isUseCert"></param> /// <param name="timeout"></param> /// <param name="Headers"></param> /// <param name="ContentType"></param> /// <param name="host"></param> /// <returns></returns> public static string Post(string xml, string url, MsMultiPartFormData form, bool isUseCert, int timeout, WebHeaderCollection Headers = null, string ContentType = null, string host = null) { System.GC.Collect(); //垃圾回收,回收没有正常关闭的http连接 string result = ""; //返回结果 HttpWebRequest request = null; HttpWebResponse response = null; Stream reqStream = null; try { //设置最大连接数 ServicePointManager.DefaultConnectionLimit = 200; //设置https验证方式 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); } /*************************************************************** * 下面设置HttpWebRequest的相关属性 * ************************************************************/ request = (HttpWebRequest)WebRequest.Create(url); request.UserAgent = USER_AGENT; request.Method = "POST"; request.Timeout = timeout * 1000; if (ContentType != null) { request.ContentType = ContentType; } if (host != null) { request.Host = host; } //设置代理服务器 //WebProxy proxy = new WebProxy(); //定义一个网关对象 //proxy.Address = new Uri(WxPayConfig.PROXY_URL); //网关服务器端口:端口 //request.Proxy = proxy; //设置POST的数据类型和长度 //request.ContentType = "text/xml"; //byte[] data = System.Text.Encoding.UTF8.GetBytes(xml); //request.ContentLength = data.Length; if (Headers != null) { for (int i = 0; i < Headers.Count; i++) { request.Headers.Add(Headers.GetKey(i), Headers.Get(i)); } } //是否使用证书 if (isUseCert) { X509Certificate2 cert = new X509Certificate2(Config.CertPath, Config.CertPwd); request.ClientCertificates.Add(cert); Log.Debug("WxPayApi", "PostXml used cert"); } //往服务器写入数据 reqStream = request.GetRequestStream(); //reqStream.Write(data, 0, data.Length); //reqStream.Close(); //处理上传的文件内容 form.PrepareFormData(); //添加最后的行 request.ContentType = "multipart/form-data; boundary=" + form.Boundary; request.Method = "POST"; foreach (var b in form.GetFormData()) { reqStream.WriteByte(b); } reqStream.Close(); //FileStream file = new FileStream(filePath, FileMode.Open); //byte[] bb = new byte[file.Length]; //file.Read(bb, 0, (int)file.Length); //file.Close(); //string fileName = Path.GetFileName(filePath); //form.AddStreamFile(fileKeyName, fileName, bb); //form.PrepareFormData(); //request.ContentType = "multipart/form-data; boundary=" + form.Boundary; //request.Method = "POST"; //Stream stream = request.GetRequestStream(); //foreach (var b in form.GetFormData()) //{ // stream.WriteByte(b); //} //stream.Close(); //获取服务端返回 response = (HttpWebResponse)request.GetResponse(); //获取服务端返回数据 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); result = sr.ReadToEnd().Trim(); sr.Close(); } catch (System.Threading.ThreadAbortException e) { Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting."); Log.Error("Exception message: {0}", e.Message); System.Threading.Thread.ResetAbort(); } catch (WebException ex) { Log.Error("HttpService", ex.ToString()); if (ex.Status == WebExceptionStatus.ProtocolError) { Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)ex.Response).StatusCode); Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)ex.Response).StatusDescription); //这里的代码能保证返回401时,正常显示信息 if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.Unauthorized || ((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.BadRequest) { response = (HttpWebResponse)ex.Response; { StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string bstr = sr.ReadToEnd(); return(bstr); } } } // //if (ex.Status == WebExceptionStatus.NameResolutionFailure) //{ // throw new WxPayException("无法访问网络"); //} //返回错误信息 throw new WxPayException(ex.ToString()); } catch (Exception e) { Log.Error("HttpService", e.ToString()); throw new WxPayException(e.ToString()); } finally { //关闭连接和流 if (response != null) { response.Close(); } if (request != null) { request.Abort(); } } return(result); }
public object UploadPic(FileData[] fds, string carphotogltype, string carid) { try { WebRequest request = (HttpWebRequest)WebRequest.Create(ServiceURL + "uploadAdver"); MsMultiPartFormData form = new MsMultiPartFormData(); form.AddFormField("devilField", "中国人"); form.AddStreamFile("fileUpload", fds[0].FileName, fds[0].FileBytes); form.PrepareFormData(); request.ContentType = "multipart/form-data; boundary=" + form.Boundary; request.Method = "POST"; Stream stream = request.GetRequestStream(); foreach (var b in form.GetFormData()) { stream.WriteByte(b); } stream.Close(); string responseContent = ""; using (HttpWebResponse res = (HttpWebResponse)request.GetResponse()) { using (Stream resStream = res.GetResponseStream()) { byte[] buffer = new byte[1024]; int read; while ((read = resStream.Read(buffer, 0, buffer.Length)) > 0) { responseContent += Encoding.UTF8.GetString(buffer, 0, read); } } res.Close(); } JavaScriptSerializer js = new JavaScriptSerializer(); List <FJ> list = js.Deserialize <List <FJ> >(responseContent); using (DBConnection dbc = new DBConnection()) { if (list.Count > 0) { dbc.ExecuteDataTable("update tb_b_carphoto set status=1 where carphotogltype=" + dbc.ToSqlValue(carphotogltype) + " and carid=" + dbc.ToSqlValue(carid)); DataTable dt = dbc.GetEmptyDataTable("tb_b_carphoto"); for (int i = 0; i < list.Count; i++) { DataRow dr = dt.NewRow(); dr["carphotoglid"] = Guid.NewGuid(); dr["FJ_ID"] = list[i].fjId; dr["status"] = 0; dr["adduser"] = SystemUser.CurrentUser.UserID; dr["addtime"] = DateTime.Now; dr["carphotogltype"] = Convert.ToInt32(carphotogltype); dr["carid"] = carid; dt.Rows.Add(dr); } dbc.InsertTable(dt); } } return(list); } catch (Exception ex) { throw ex; } }