zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    jquery.stop()停止动画
    字符串转义
    CSS规范 (命名)- 分类方法
    inline-block 间距
    jquery中offset(),position()
    PHP把数组转换为JSON字符串
    json对象
    C#-静态实例
    C#-readonly与const区别
    SQL-事务隔离级别与锁
  • 原文地址:https://www.cnblogs.com/zlj-rechio/p/9953548.html
Copyright © 2011-2022 走看看