生成微信小程序二维码并上传到FTP 服务器

生成微信小程序二维码并上传到FTP 服务器

public static bool codeImage(string scene, string page,int status,out string t)
{
bool result = true;
string imgurl = string.Empty;
string sAPPID = “”;
string sAPPSECRET = “”;
if (status == 0)
{
sAPPID = ConfigurationManager.AppSettings[“cAPPID”];
sAPPSECRET = ConfigurationManager.AppSettings[“cAPPSECRET”];
}
else if (status == 1) {
sAPPID = ConfigurationManager.AppSettings[“dAPPID”];
sAPPSECRET = ConfigurationManager.AppSettings[“dAPPSECRET”];
}
//string page = ConfigurationManager.AppSettings[“pages”];
string ftp = ConfigurationManager.AppSettings[“Ftp”];
string user = ConfigurationManager.AppSettings[“User”];
string pass = ConfigurationManager.AppSettings[“Pass”];
try
{

            string serviceAddress = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + sAPPID + "&secret=" + sAPPSECRET;
           
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "GET";
            request.ContentType = "text/html;charset=utf-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            MpToken mptoken = FromJSON<MpToken>(retString);
            string token = mptoken.access_token;
            string url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token;
           
            //Dictionary<string, string> map = new Dictionary<string, string>();
           // map.Add("r", "0");
           // map.Add("g", "0");
            //map.Add("b", "0");
            CodeEntity entity = new CodeEntity(page, scene, 360, false);
            using (HttpClient client = new HttpClient())
            {

                string aa = entity.ToString();
                
                HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(entity));
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                HttpResponseMessage message = client.PostAsync(url, httpContent).Result;

                byte[] tt = message.Content.ReadAsByteArrayAsync().Result;

                // string tex = System.Text.Encoding.Default.GetString(tt);

                //MpToken a = JsonConvert.DeserializeObject<MpToken>(tex);
                //string serviceAddress1 = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+ a.access_token;
                //HttpResponseMessage message1 = client.PostAsync(serviceAddress1, httpContent).Result;

              string imgName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
              //  string imgPath = "D:\\CodeImage";
              //  string Path1 = @"D:\CodeImage\" + imgName;
              string a = JsonConvert.SerializeObject(entity);

                File.WriteAllBytes(@Path1, tt);
              string imgPath = AppDomain.CurrentDomain.BaseDirectory+"images";
              //  if (!Directory.Exists(imgPath))
              //  {
              //      //没有就创建
              //      Directory.CreateDirectory(imgPath);
              //  }
                //string fromFilePath = Path.Combine(imgPath, imgName);
                //FileStream fileStream = new FileStream(fromFilePath, FileMode.Open, FileAccess.Read);
                //fileStream.Read(tt, 0,tt.Length);
                //fileStream.Close();
                //string toFilePath = Path.Combine(imgPath,imgName);
                //FileStream toStream = new FileStream(toFilePath, FileMode.Open, FileAccess.ReadWrite);
                //toStream.Write(tt, 0, tt.Length);
                //toStream.Close();
                string text = "";
          FtpUploadFile(tt, imgName,ref text);
                t = "/CreditStoreOn/" + imgName;
            }
        }
        catch (Exception e)
        {
            t = e.Message;
            return false;
        }
        return result;
    }

///
/// 上传文件到FTP服务器
///
/// 本地带有完整路径的文件名
/// 报告进度的处理(第一个参数:总大小,第二个参数:当前进度)
/// 是否下载成功
public static bool FtpUploadFile(byte[] bmpBytes, string filename, ref string text, Action<int, int> updateProgress = null)
{
FtpWebRequest reqFTP;
Stream stream = null;
FileStream fs = null;
string FtpServerIP = ConfigurationManager.AppSettings[“Ftp”];

        string FtpUserID = ConfigurationManager.AppSettings["User"];

        string FtpPassword = ConfigurationManager.AppSettings["Pass"];

        try
        {


            MemoryStream ms = new MemoryStream();
           // bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            //byte[] bmpBytes = ms.GetBuffer();
           // ms.Close();

            if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
            {
                throw new Exception("ftp上传目标服务器地址未设置!");
            }
            Uri uri = new Uri(FtpServerIP + "/CreditStoreOn/" + filename);
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
            reqFTP.KeepAlive = false;
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;//向服务器发出下载请求命令
            reqFTP.ContentLength = bmpBytes.Length;//为request指定上传文件的大小
            int buffLength = 10;
            stream = reqFTP.GetRequestStream();

            int allbye = bmpBytes.Length;
            //更新进度 
            if (updateProgress != null)
            {
                updateProgress(allbye, 0);//更新进度条 
            }
            int startbye = 0;
            var count = allbye / buffLength;
            var i = 0;
            var bl = true;
            while (bl)
            {
                if (i == count)
                {
                    buffLength = allbye % buffLength;

                    bl = false;
                }
                else
                {
                    startbye = i * 10;
                }
                stream.Write(bmpBytes, startbye, buffLength);

                //更新进度 
                if (updateProgress != null)
                {
                    updateProgress(allbye, startbye);//更新进度条 
                }
                i++;
                Console.WriteLine(i);
            }

            //text = System.Text.Encoding.Default.GetString(bmpBytes);
            stream.Close();



           
            return true;

        }
        catch (Exception ex)
        {
            string message = ex.Message;
            return false;
            throw;
        }
        finally
        {
            if (fs != null)
            {
                fs.Close();
            }
            if (stream != null)
            {
                stream.Close();
            }

        }
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值