• 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 + " ");
    byte[] enterER = Encoding.ASCII.GetBytes(" ");
    ////提交文件
    if (files != null)
    {
    string fformat = "Content-Disposition:form-data; name="file";filename="{0}" Content-Type:{1} ";
    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); //添加
    }
    }

    byte[] foot_data = Encoding.UTF8.GetBytes("--" + boundary + "-- "); //项目最后的分隔符字符串需要带上--
    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

  • 相关阅读:
    ASP.NET WebForm Best Practice 之ViewState
    我会为开源和自由学习,使用JAVA.但我决不会为了开源和自由放弃.NET
    EXT调用ASP.NET AJAX WebService
    我的2007
    博客园迎新春对联
    NBear.Mapping使用教程(2):NBear.Mapping的配置系统
    NBear.Mapping使用教程(3):第一个简单例子
    使用LumaQQ来开发QQ机器人
    解决方案迁移到Visual Studio 2008的一些相关问题
    NBear.Mapping使用教程(4):实体对象与ADO.NET对象的转换
  • 原文地址:https://www.cnblogs.com/zlj-rechio/p/9953548.html
Copyright © 2020-2023  润新知