.net mvc 使用盛派Senparc.Weixin 上传图片接口

首先获取微信签名,Controller代码:

public ActionResult MutualHelpAdd()
        {
            var jssdkUiPackage = JSSDKHelper.GetJsSdkUiPackage(WeChatParameter._appID, WeChatParameter._appSecret, Request.Url.AbsoluteUri);
            ViewBag.AppId = WeChatParameter._appID;
            ViewBag.Timestamp = jssdkUiPackage.Timestamp;
            ViewBag.NonceStr = jssdkUiPackage.NonceStr;
            ViewBag.Signature = jssdkUiPackage.Signature;

            return View();
        }
View Code

视图代码:

  wx.config({
            //debug: true,
            appId: '@ViewBag.AppId',
            timestamp: '@ViewBag.Timestamp',
            nonceStr: '@ViewBag.NonceStr',
            signature: '@ViewBag.Signature',
            jsApiList: [
               'chooseImage',
               'previewImage',
               'uploadImage',
               'downloadImage'
            ]
        });

        wx.ready(function () {

            // 5 图片接口
            // 5.1 拍照、本地选图
            var images = {
                localId: [],
                serverId: []
            };
            document.querySelector('#btnAddImage').onclick = function () {
                wx.chooseImage({
                    count: 3, // 默认9,设置可以同时上传的图片数量
                    sizeType: ['original', 'compressed'],     // 可以指定是原图还是压缩图,默认二者都有
                    sourceType: ['album', 'camera'],         // 可以指定来源是相册还是相机,默认二者都有
                    success: function (res) {
                        images.localId = res.localIds;
                        //alert('已选择 ' + res.localIds.length + ' 张图片');

                        var i = 0, length = images.localId.length;
                        images.serverId = [];
                        function upload() {
                            wx.uploadImage({
                                localId: images.localId[i],
                                success: function (res) {
                                    i++;
                                    //alert('已上传:' + i + '/' + length);
                                    images.serverId.push(res.serverId);

                                    //TODO: res.serverId 就是 media_id,根据它去微信服务器读取图片数据:自定义上传到自己服务器
                                    var imageJson = $("#hdImageJson").val();

                                    $.ajax({
                                        type: 'post',
                                        url: '/Common/AddImage',
                                        async: false,
                                        data: {
                                            media_id: res.serverId,
                                            imageJson: imageJson,
                                            folderName:"MutualHelp"
                                        },
                                        success: function (data) {
                                            if (data.ImageUrl != '') {
                                                // 返回 图片在我们自己的服务器的url
                                                var img = "<img class='task_image' src='/images/" + data.ImageUrl + "'/>";
                                                $("#imgList").append(img);
                                                $("#hdImageJson").val(data.ImageJson);
                                            }
                                        },
                                        error: function (err) {

                                        }
                                    })

                                    if (i < length) {
                                        upload();
                                    }
                                },
                                fail: function (res) {
                                    alert(JSON.stringify(res));
                                }
                            });
                        }
                        upload();

                    }
                });
            };

        });
View Code

图片保存到本地服务器方法:

  /// <summary>
        /// 公用 微信 上传图片方法
        /// </summary>
        /// <param name="media_id"></param>
        /// <param name="imageJson"></param>
        /// <returns></returns>
        public JsonResult AddImage(string media_id, string imageJson,string folderName)
        {
            var imgUrl = "";
            try
            {
                List<ImageList> curImageResult;
                if (!string.IsNullOrEmpty(imageJson))
                {
                    curImageResult = JsonConvert.DeserializeObject<List<ImageList>>(imageJson);
                }
                else
                {
                    curImageResult = new List<ImageList>();
                }
                var accessToken = AccessTokenContainer.TryGetAccessToken(WeChatParameter._appID, WeChatParameter._appSecret);

                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                MediaApi.Get(accessToken, media_id, stream);
                Image img = Image.FromStream(stream);
                var imgName = DateTime.Now.ToString("yyyyMMddhhss");
                var fileSaveUrl =string.Format(FilePath + "/{0}/" + imgName + ".jpg", folderName);
                imgUrl = string.Format("/{0}/" + imgName + ".jpg", folderName);
                img.Save(fileSaveUrl);

                var imageEntity = new ImageList
                {
                    ImageKey = imgName,
                    ImageUrl = imgUrl,
                    UploadTime = DateTime.Now
                };
                curImageResult.Add(imageEntity);

                imageJson = JsonConvert.SerializeObject(curImageResult);
            }
            catch (Exception ex)
            {
                imgUrl = "";
            }

            var result = new
            {
                ImageJson = imageJson,
                ImageUrl = imgUrl
            };
            return Json(result);
        }
View Code

 

posted @ 2017-02-20 14:25  厦门_成  阅读(805)  评论(0编辑  收藏  举报