Example #1
0
        /// <summary>
        /// 同步上传文件
        /// </summary>
        /// <param name="fileInfo">文件信息</param>
        /// <param name="toUserName">发送人UserName,其实没什么用,但是官方有这个参数</param>
        /// <returns></returns>
        public UploadMediaResponse UploadFile(FileInfo fileInfo, string toUserName)
        {
            string             postUrl            = uploadHost + "/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json";
            int                bufferLength       = 512 * 1024;
            string             datetime           = DateTime.Now.ToString("ddd MMM dd yyyy HH:mm:ss", CultureInfo.CreateSpecificCulture("en-US")) + " GMT+0800 (中国标准时间)";
            UploadMediaRequest uploadMediaRequest = new UploadMediaRequest()
            {
                UploadType    = 2,
                BaseRequest   = baseRequest,
                ClientMediaId = Utils.GetJavaTimeStamp(),
                TotalLen      = fileInfo.Length,
                StartPos      = 0,
                DataLen       = fileInfo.Length,
                MediaType     = 4,
                FromUserName  = user.UserName,
                ToUserName    = toUserName,
                FileMd5       = Utils.GetFileMD5Hash(fileInfo)
            };
            UploadMediaResponse response = null;

            //文件大小超过512Kb,分块上传。
            if (fileInfo.Length > bufferLength)
            {
                int    chunks     = (int)Math.Ceiling((double)fileInfo.Length / bufferLength);
                byte[] buffer     = new byte[bufferLength];
                Stream readStream = fileInfo.OpenRead();
                int    chunk      = 0;
                int    readLength = 0;
                while ((readLength = readStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    List <FormDataItem> dataList = new List <FormDataItem>()
                    {
                        new FormDataItem("id", "WU_FILE_" + uploadMedia.Count),
                        new FormDataItem("name", fileInfo.Name),
                        new FormDataItem("type", MimeMapping.GetMimeMapping(fileInfo.Name)),
                        new FormDataItem("lastModifiedDate", datetime),
                        new FormDataItem("size", fileInfo.Length.ToString()),
                        new FormDataItem("chunks", chunks.ToString()),
                        new FormDataItem("chunk", chunk.ToString()),
                        new FormDataItem("mediatype", GetMediaType(fileInfo.Extension)),
                        new FormDataItem("uploadmediarequest", JsonConvert.SerializeObject(uploadMediaRequest, Newtonsoft.Json.Formatting.None)),
                        new FormDataItem("webwx_data_ticket", httpClient.CookieContainer.GetCookies(new Uri(cookieRedirectUri))["webwx_data_ticket"].Value),
                        new FormDataItem("pass_ticket", passTicket),
                        new FormDataItem("filename", fileInfo.Name, buffer, readLength)
                    };
                    string result = httpClient.PostMutipart(postUrl, dataList);
                    response = JsonConvert.DeserializeObject <UploadMediaResponse>(result);
                    chunk++;
                }
            }
            else
            {
                byte[] buffer                = new byte[fileInfo.Length];
                Stream readStream            = fileInfo.OpenRead();
                int    readLength            = readStream.Read(buffer, 0, buffer.Length);
                List <FormDataItem> dataList = new List <FormDataItem>()
                {
                    new FormDataItem("id", "WU_FILE_" + uploadMedia.Count),
                    new FormDataItem("name", fileInfo.Name),
                    new FormDataItem("type", MimeMapping.GetMimeMapping(fileInfo.Name)),
                    new FormDataItem("lastModifiedDate", datetime),
                    new FormDataItem("size", fileInfo.Length.ToString()),
                    new FormDataItem("mediatype", GetMediaType(fileInfo.Extension)),
                    new FormDataItem("uploadmediarequest", JsonConvert.SerializeObject(uploadMediaRequest, Newtonsoft.Json.Formatting.None)),
                    new FormDataItem("webwx_data_ticket", httpClient.CookieContainer.GetCookies(new Uri(cookieRedirectUri))["webwx_data_ticket"].Value),
                    new FormDataItem("pass_ticket", passTicket),
                    new FormDataItem("filename", fileInfo.Name, buffer, readLength)
                };
                string result = httpClient.PostMutipart(postUrl, dataList);
                response = JsonConvert.DeserializeObject <UploadMediaResponse>(result);
            }
            uploadMedia.Add(fileInfo.Name, response.MediaId);
            return(response);
        }
Example #2
0
        /// <summary>
        /// 同步发送文件,自动分块上传,文件较大可能会卡住进程,建议异步发送
        /// </summary>
        /// <param name="fileInfo">文件信息</param>
        /// <param name="toUserName">发送人UserName</param>
        /// <returns></returns>
        public SendMsgResponse SendMsg(FileInfo fileInfo, string toUserName)
        {
            string mediaId = string.Empty;

            if (uploadMedia.Keys.Contains(fileInfo.Name))
            {
                mediaId = uploadMedia[fileInfo.Name];
            }
            else
            {
                UploadMediaResponse uploadMediaResponse = UploadFile(fileInfo, toUserName);
                mediaId = uploadMediaResponse.MediaId;
            }
            string          mime     = MimeMapping.GetMimeMapping(fileInfo.Name);
            string          time     = Utils.GetJavaTimeStamp().ToString();
            SendMsgResponse response = null;

            if (mime.StartsWith("image"))
            {
                string sendMsgUrl = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxsendmsgimg?fun=async&f=json&lang=zh_CN&pass_ticket={0}", passTicket);
                SendMediaMsgRequest sendImgMsgRequest = new SendMediaMsgRequest()
                {
                    BaseRequest = baseRequest,
                    Msg         = new MediaMsg()
                    {
                        ClientMsgId  = time,
                        FromUserName = user.UserName,
                        LocalID      = time,
                        MediaId      = mediaId,
                        ToUserName   = toUserName,
                        Type         = MSGTYPE.MSGTYPE_IMAGE
                    },
                    Scene = 0
                };
                response = httpClient.PostJson <SendMsgResponse>(sendMsgUrl, sendImgMsgRequest);
            }
            else if (mime.StartsWith("video"))
            {
                string sendMsgUrl = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxsendvideomsg?fun=async&f=json&lang=zh_CN&pass_ticket={0}", passTicket);
                SendMediaMsgRequest sendImgMsgRequest = new SendMediaMsgRequest()
                {
                    BaseRequest = baseRequest,
                    Msg         = new MediaMsg()
                    {
                        ClientMsgId  = time,
                        FromUserName = user.UserName,
                        LocalID      = time,
                        MediaId      = mediaId,
                        ToUserName   = toUserName,
                        Type         = MSGTYPE.MSGTYPE_IMAGE
                    },
                    Scene = 0
                };
                response = httpClient.PostJson <SendMsgResponse>(sendMsgUrl, sendImgMsgRequest);
            }
            else
            {
                string         sendMsgUrl        = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxsendappmsg?fun=async&f=json&lang=zh_CN&pass_ticket={0}", passTicket);
                SendMsgRequest sendAppMsgRequest = new SendMsgRequest()
                {
                    BaseRequest = baseRequest,
                    Msg         = new Msg()
                    {
                        ClientMsgId  = time,
                        Content      = string.Format("<appmsg appid='wxeb7ec651dd0aefa9' sdkver=''><title>{0}</title><des></des><action></action><type>6</type><content></content><url></url><lowurl></lowurl><appattach><totallen>{1}</totallen><attachid>{2}</attachid><fileext>{3}</fileext></appattach><extinfo></extinfo></appmsg>", fileInfo.Name, fileInfo.Length, mediaId, fileInfo.Extension.Substring(1)),
                        FromUserName = user.UserName,
                        ToUserName   = toUserName,
                        LocalID      = time,
                        Type         = MSGTYPE.MSGTYPE_DOC
                    },
                    Scene = 0
                };
                response = httpClient.PostJson <SendMsgResponse>(sendMsgUrl, sendAppMsgRequest);
            }
            return(response);
        }