请求端:
var upurl = Config.GetValue("fileupUrl"); HttpPostedFile file = files[0]; MemoryStream memoryStream = new MemoryStream(); file.InputStream.CopyTo(memoryStream); byte[] fileBytes = memoryStream.ToArray(); object sendScObj = new { relaPath = virtualPath, fileName = fileName }; ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = delegate { return true; } }; using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(handler))//若想手动设置Cookie则必须设置UseCookies = false { var fileContent = new ByteArrayContent(fileBytes); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file", FileName = fileName }; var formDataContent = new MultipartFormDataContent(); formDataContent.Add(fileContent); formDataContent.Headers.Add("UserName", ""); formDataContent.Headers.Add("PassWord", ""); formDataContent.Headers.Add("SendPlatCode", ""); var response = await client.PostAsync(upurl, formDataContent); response.EnsureSuccessStatusCode(); }
接收端:
[HttpPost] public async Task<object> syncReceStream() { #region 授权 string AuthcodeID = ""; var authResult = Authorization(out AuthcodeID); if (authResult.Code != ClientCode.Succeed) { return authResult; } var ips = Config.GetValue("yxIP"); var bendiPath = Config.GetValue("BendiPath"); if (string.IsNullOrEmpty(bendiPath) || string.IsNullOrEmpty(ips) || !ips.Contains(AuthcodeID)) { authResult.Code = ClientCode.FindNull; authResult.ErrorMessage = "未找到网络"; return authResult; } #endregion ApiResultModel apiModel = new ApiResultModel(); try { //获取流 var requestfile = System.Web.HttpContext.Current.Request.Files[0]; if (requestfile != null && requestfile.ContentLength > 0) { var request = await Request.Content.ReadAsStringAsync(); if (string.IsNullOrEmpty(request)) { apiModel.Code = ClientCode.FindNull; apiModel.ErrorMessage = "未找到参数"; return apiModel; } var model = Util.Json.ToObject<AnnexInfoEntity>(request.ToString()); var RoutePath = bendiPath + model.RelaPath; if (!System.IO.Directory.Exists(RoutePath)) { System.IO.Directory.CreateDirectory(RoutePath); } //本地文件夹 requestfile.SaveAs(RoutePath); apiModel.Code = ClientCode.Succeed; } else { apiModel.Code = ClientCode.Exception; apiModel.ErrorMessage = "文件异常"; } } catch (Exception ex) { apiModel.Code = ClientCode.Exception; apiModel.ErrorMessage = ex.Message; } return apiModel; }
标签:formDataContent,apiModel,接口,ClientCode,authResult,var,new,上传,httpclient From: https://www.cnblogs.com/misakayoucn/p/17758897.html