/// <summary>
/// 导出到通讯录 生成微信头像跟VCF文件
/// </summary>
/// <returns></returns>
[Route("User/Mp_Vcf")]
[HttpPost]
public string Mp_Vcf()
{
var UserId = RequestHelper.GetStringParam("UserId", string.Empty).Trim();
var https = RequestHelper.GetStringParam("https", string.Empty).Trim();
try
{
if (string.IsNullOrEmpty(UserId))
return JsonHelper.JsonFormat(202, "操作失败", "用户信息ID不能为空!", DBNull.Value);
if (string.IsNullOrEmpty(https))
return JsonHelper.JsonFormat(202, "操作失败", "用户信息地址不能为空!", DBNull.Value);
ProcApp p = new ProcApp();
DataSet ds = p.Select_MpVcf(UserId);
if (ds.Tables[0].Rows.Count > 0)
return JsonHelper.JsonFormat(200, "查询成功", "查询成功!", ds.Tables[0]);
else
{
ds = p.GetAgentInfo_MpInfo(UserId);
if (ds.Tables[0].Rows.Count > 0)
{
string UserImg = ds.Tables[0].Rows[0]["UserImg"].ToString();
string UserTitle = ds.Tables[0].Rows[0]["UserTitle"].ToString();
string UserAllianName = ds.Tables[0].Rows[0]["UserAllianName"].ToString();
string WeChat = ds.Tables[0].Rows[0]["WeChat"].ToString();
string RealName = ds.Tables[0].Rows[0]["RealName"].ToString();
string UserPhone = ds.Tables[0].Rows[0]["UserPhone"].ToString();
string AgentName = ds.Tables[0].Rows[0]["AgentName"].ToString();
string UpUserImg = string.Empty;
string strUrl_Vcf = UserPhone + DateTime.Now.Millisecond; //一定要随机生成VCF文件 不然会文件内容会一致累加
FileStream fs = new FileStream((@"" + System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Filters\\" + strUrl_Vcf + ".vcf"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("BEGIN:VCARD");
sw.WriteLine("VERSION:3.0");
sw.WriteLine("N;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:" + Str2ASCII(RealName));
sw.WriteLine("N:" + WeChat + "");
sw.WriteLine("FN:" + WeChat + "");
sw.WriteLine("ORG:" + RealName + "");
sw.WriteLine("TITLE:" + UserTitle + "");
sw.WriteLine("TEL;type=CELL;type=pref:" + UserPhone + "");
sw.WriteLine("item2.URL;type=pref:" + https + "");
sw.WriteLine("NOTE:三草两木(SASELOMO)始终从大自然中获取神奇力量,将传统美学文化与“极减-自然护肤”理念相结合,用心研制纯净、自然、有效的护肤品,帮助女性回归真实、自然、惊喜的肌肤状态!");
if (string.IsNullOrEmpty(UserImg))
UserImg = "https://img.saselomo.com/WxMp_Vcf/WxMpHead.png";
UpUserImg = SaveImageFromWeb(UserImg);
if (UpUserImg == "fail")
return JsonHelper.JsonFormat(202, "上传文件失败", "上传文件失败!", DBNull.Value);
else
sw.WriteLine("PHOTO;ENCODING=B;TYPE=PNG:" + GetBase64FromImage(UpUserImg));
sw.WriteLine("END:VCARD");
sw.Flush(); sw.Close();
fs.Dispose(); fs.Close();
strUrl_Vcf = ConfigurationManager.AppSettings["WxVcf_Url"] + "Filters/" + strUrl_Vcf + ".vcf";
if (!string.IsNullOrEmpty(UpUserImg) && !string.IsNullOrEmpty(strUrl_Vcf))
{
if (p.Insert_MpVcf(UserId, UpUserImg, strUrl_Vcf) > 0)
{
ds = p.Select_MpVcf(UserId);
if (ds.Tables[0].Rows.Count > 0)
return JsonHelper.JsonFormat(200, "查询成功", "查询成功!", ds.Tables[0]);
else
return JsonHelper.JsonFormat(202, "查询失败", "添加成功,查询失败!", DBNull.Value);
}
else
return JsonHelper.JsonFormat(202, "查询失败", "添加失败,查询失败!", DBNull.Value);
}
else
return JsonHelper.JsonFormat(202, "查询失败", "上传的图片跟文件失败!", DBNull.Value);
}
else
return JsonHelper.JsonFormat(202, "查询失败", "查询不到对应用户的数据!", DBNull.Value);
}
}
catch (Exception ex)
{
FileLog.Info("【User/Mp_Vcf】{UserId:" + UserId + "}[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + ex.Message);
return JsonHelper.JsonFormat(204, "操作失败", "网络异常,请联系管理员!", DBNull.Value);
}
}
/// <summary>
/// 含中文字符串转ASCII
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string Str2ASCII(String str)
{
try
{
//这里我们将采用2字节一个汉字的方法来取出汉字的16进制码
byte[] textbuf = Encoding.Default.GetBytes(str);
//用来存储转换过后的ASCII码
string textAscii = string.Empty;
for (int i = 0; i < textbuf.Length; i++)
{
textAscii += textbuf[i].ToString("X");
}
return textAscii;
}
catch (Exception ex)
{
return "含中文字符串转ASCII异常";
}
}
/// <summary>
/// 图片转成64进制 流
/// </summary>
/// <param name="imagefile"></param>
/// <returns></returns>
public string GetBase64FromImage(string imagefile)
{
string strbaser64 = "";
try
{
var myWebClient = new WebClient { Credentials = CredentialCache.DefaultCredentials };//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
var imgByte = myWebClient.DownloadData(imagefile);
var ms = new MemoryStream(imgByte) { Position = 0 };
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
strbaser64 = Convert.ToBase64String(arr);
}
catch (Exception ex)
{
throw new Exception("Something wrong during convert!");
}
return strbaser64;
}
/// <summary>
/// 保存web图片到 阿里云
/// </summary>
/// <param name="imgUrl">web图片路径</param>
/// <returns></returns>
public string SaveImageFromWeb(string imgUrl)
{
string fileName = "WxMp";
string defaultType = ".jpg";
string[] imgTypes = new string[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
string imgType = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("."));
foreach (string it in imgTypes)
{
if (imgType.ToLower().Equals(it))
break;
if (it.Equals(".bmp"))
imgType = defaultType;
}
var strUrl = string.Format("WxMp_Vcf/{0}/{1}/{2}", DateTime.Now.ToString("yyyy-MM-dd"), fileName, DateTime.Now.ToString("yyyyMMddHHmmssffff") + imgType);
var myWebClient = new WebClient { Credentials = CredentialCache.DefaultCredentials };//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
var imgByte = myWebClient.DownloadData(imgUrl);
var fso = new MemoryStream(imgByte) { Position = 0 };
string strReturn = UploadFile2Aliyun(fso, strUrl);
fso.Close();
if (strReturn != "succeeded") //上传到阿里云
return "fail";
else
return ConfigurationManager.AppSettings["aliImageUrl"] + strUrl;
}
/// <summary>
/// 上传文件到aliyun的oss
/// </summary>
/// <param name="stream">文件流</param>
/// <param name="key">文件路径</param>
/// <param name="bucketName">容器名</param>
/// <returns></returns>
public string UploadFile2Aliyun(Stream stream, string key, string bucketName = "sclm-drp")
{
var accessKeyId = ConfigurationManager.AppSettings["AccessKeyId"];
var accessKeySecret = ConfigurationManager.AppSettings["AccessKeySecret"];
var endpoint = ConfigurationManager.AppSettings["Endpoint"];
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
var rntMsg = "";
try
{
//上传文件
client.PutObject(bucketName, key, stream);
//上传字符串
// client.PutObject(bucketName, key, requestContent);
//rntMsg = string.Format("Put object:{0} succeeded", key);
rntMsg = string.Format("succeeded");
}
catch (OssException ex)
{
rntMsg = string.Format("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
rntMsg = string.Format("Failed with error info: {0}", ex.Message);
}
return rntMsg;
}