调用腾讯的二维码接口,需要把二维码图片保存到本地
public string SendQCode(string studentid)
{
if (studentid != "")
{
QrCodeApi qrcode = new QrCodeApi();
string QRCode = qrcode.GetQrcode( studentid);
string qcurl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + QRCode;
string path = Server.MapPath("~/Data/image/" + studentid + ".jpg");
//判断二维码图片是否存在,如果存在删除
if (File.Exists(path))
{
//File.Delete(Path.GetFullPath(path));
File.Delete(path);
}
//直接保存二维码到本地
Downloader.SaveQrCodeImage(qcurl, path);
return "http://....../image/" + studentid + ".jpg";
}
else
{
return "";
}
}
主要做的是保存方法SaveQrCodeImage
/// <summary>
/// 根据Ticket获取二维码图片保存在本地
/// </summary>
/// <param name="scene_id">二维码场景id</param>
/// <param name="imgPath">图片存储路径</param>
public static void SaveQrCodeImage(string url, string imgPath)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();
string strpath = myResponse.ResponseUri.ToString();
WebClient mywebclient = new WebClient();
try
{
mywebclient.DownloadFile(strpath, imgPath);
}
catch (Exception ex)
{
throw new Exception("获取二维码图片失败!");
//throw ex;
}
}
}
还有一种是由于二维码过期所以
自己在项目中专业建一个图片页面,访问该页面会加载图片。
由于做了两次封装,故此 先调用腾讯的接口,返回的是图片路径,之后在保存改路经资源返回
public void GetTengxunQCode(string studentid)
{
if (studentid != "")
{
QrCodeApi qrcode = new QrCodeApi();
string QRCode = qrcode.GetQrcode(studentid);
prlimg = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + QRCode;
WebClient wc = new WebClient();
byte[] b = wc.DownloadData(prlimg);
Response.ContentType = "image/jpg";
Response.BinaryWrite(b);
Response.Flush();
Response.End();
}
}
用WebClient类
WebClient wc = new WebClient();
byte[] b = wc.DownloadData(prlimg);
Response.ContentType = "image/jpg";
Response.BinaryWrite(b);
Response.Flush();
Response.End();
即可