撸码成魔

C#.Net 配合小程序实现经过第三方服务器中转文件

电脑版发表于:2018/11/26 9:41


             


   某些时候,微信小程序前段上传文件的时候需要经过第三方服务器再将文件上传到客户的服务器;操作如下:

1:(小程序内向中端服务器发起请求)

wx.uploadFile({
url: getApp().globalData.appUrl + '/phone/upimg.aspx',//中端的处理界面
filePath: filep,//本次传输的文件
name: 'file',//文件的name
formData: {//formData为自定义参数对象
index: i + 1,
Type: "Bill-CWDZ",
OrderID: _tempBid,
SendType: "wx",
u: app.globalData.url//当前小程序所在服务器url
},
success: function (ex) {

}

2:中端服务器的操作

 if (Context.Request["Type"] != null && Context.Request["u"] != null)
            {
                string _url = string.Format("{0}/Util/UpdataPZImgPhone.aspx", Context.Request["u"].ToString());
                //处理接收到的请求,解析请求内容与大小
                var curRequest = HttpContext.Current.Request;
                byte[] inputBytes;
                int inputStreamLength;
                using (var inputStream = curRequest.InputStream)
                {
                    inputStreamLength = Convert.ToInt32(inputStream.Length);
                    inputBytes = new byte[inputStreamLength];
                    inputStream.Read(inputBytes, 0, inputStreamLength);
                    inputStream.Close();
                }

                //构造真正的请求
                //请求方式为POST,请求内容格式、内容与接收到的请求保持一致
                var request = (HttpWebRequest)WebRequest.Create(_url);
                request.Method = "POST";
                request.ContentType = curRequest.ContentType;
                request.ContentLength = curRequest.ContentLength;
                using (var requestStream = request.GetRequestStream())//真正的请求目标服务器,把文件传输过去
                {
                    requestStream.Write(inputBytes, 0, inputStreamLength);
                    requestStream.Close();
                }

                //Log.Instance.Info("步骤2");

                //获取请求返回响应结果
                using (var _resp = request.GetResponse())
                {
                    Stream stream = _resp.GetResponseStream();

                    //Log.Instance.Info("步骤3");

                    //处理返回结果
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        _result = reader.ReadToEnd();
                        reader.Close();
                    }              
                    stream.Close();
                    stream = null;
                    _url = null;
                }
            }


关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢