[转]WebApi 后端文件传输至远程服务器

/*

功能说明:微信退款需要有数字证书,而我们公司是做小程序平台的,会帮商家自动退款,所以会要求商家把微信证书上传至我们服务器,以便

微信退款。

使用HttpPostedFile 接受前端上传的文件,再使用

*/

#region 证书上传 UploadCertificate
/// <summary>
/// 证书上传
/// </summary>
/// <returns></returns>
[HttpPost]
public IHttpActionResult UploadCertificate()
{

//此字段代表商家证书存储的文件夹
string enterpriseId = "test";
OperationResult response = new OperationResult
{
Code = OperationResultType.IllegalOperation,
Message = "不是有效的p12证书文件"
};
try
{
HttpFileCollection filelist = HttpContext.Current.Request.Files;
if (filelist != null && filelist.Count > 0)
{
HttpPostedFile file = filelist[0];
//文件名
string fileName = file.FileName;
if (string.IsNullOrWhiteSpace(fileName) || !fileName.Contains("."))
{
return Json(response);
}
var fileNameSplit = fileName.Trim(new[] { '"' }).Split('.');
//文件后缀名
string fileExName = fileNameSplit[fileNameSplit.Length - 1];
if (!fileExName.Equals("p12"))
{
return Json(response);
}

//上传文件至远程服务器
string res = PostResponse($"url",new HttpPostedFile[] { file });
if (!string.IsNullOrWhiteSpace(res))
{
return Json(JsonUtility.DeserializeObject<OperationResult>(res));
}
}
}
catch (Exception ex)
{
LogHelper.Error("UploadCertificate-error", ex);
}
return Json(response);
}

#endregion

 

#region 使用WebRequest构建多媒体文件上传远程服务器 PostResponse
/// <summary>
/// 发起httpPost 请求,可以上传文件
/// </summary>
/// <param name="url">请求的地址</param>
/// <param name="files">文件</param>
/// <returns></returns>
public static string PostResponse(string url, HttpPostedFile[] files)
{
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
//request.Credentials = CredentialCache.DefaultCredentials;
request.Expect = "";

MemoryStream stream = new MemoryStream();


byte[] line = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
byte[] enterER = Encoding.ASCII.GetBytes("\r\n");
////提交文件
if (files != null)
{
string fformat = "Content-Disposition:form-data; name=\"file\";filename=\"{0}\"\r\nContent-Type:{1}\r\n\r\n";
foreach (HttpPostedFile file in files)
{
//#region HttpPostedFile.InputStream=>byte[]
//Stream inputStream = file.InputStream;//new MemoryStream();
//byte[] bytes = new byte[stream.Length];
//#endregion
var fileStream = file.InputStream;
var buffer = new byte[1024];
int bytesRead; // =0

stream.Write(line, 0, line.Length); //项目分隔符
string s = string.Format(fformat, file.FileName, file.ContentType);
byte[] data = Encoding.UTF8.GetBytes(s);
stream.Write(data, 0, data.Length);
//stream.Write(bytes, 0, bytes.Length);//文件内容
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
stream.Write(enterER, 0, enterER.Length); //添加\r\n
}
}

byte[] foot_data = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n"); //项目最后的分隔符字符串需要带上-- 
stream.Write(foot_data, 0, foot_data.Length);

request.ContentLength = stream.Length;
Stream requestStream = request.GetRequestStream(); //写入请求数据
stream.Position = 0L;
stream.CopyTo(requestStream); //
stream.Close();

requestStream.Close();
try
{
#region
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
}

#endregion
//HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamIn = response.GetResponseStream();

StreamReader reader = new StreamReader(streamIn);
string result = reader.ReadToEnd();
reader.Close();
streamIn.Close();
response.Close();

return result;
}
catch (Exception ex)
{
throw ex;
}
#endregion

  


---------------------
作者:小小周
来源:CNBLOGS
原文:https://www.cnblogs.com/zlj-rechio/p/9953548.html
版权声明:本文为作者原创文章,转载请附上博文链接!

posted @ 2019-07-23 16:36  JackieZhengChina  阅读(190)  评论(0编辑  收藏  举报