public JsonResult ResetPwd(int id = 0) { PublicUser publicUser = ncBase.CurrentEntities.PublicUser.Where(o => o.UserID == id).FirstOrDefault(); if (publicUser.IsNull()) { return(Json(new { status = 1, msg = "没有找到用户!(用户ID:" + id + ")" })); } string passWordAdorn = ConfigUtility.GetValue("PassWordAdorn"); string passWord = string.Empty; if (string.IsNullOrEmpty(publicUser.Tel)) { passWord = Convert.ToString(publicUser.UserID); } PublicUserModel loginUser = this.GetLoginUser(); passWord = publicUser.Tel; publicUser.Password = StringUtility.ToMd5String(passWordAdorn + passWord); ncBase.CurrentEntities.SaveChanges(); OperatorLog operatorLog = new OperatorLog(); operatorLog.Note = "重置密码,被重置用户ID:" + publicUser.UserID + " 新密码:" + passWord; operatorLog.Type = 1; operatorLog.Uid = loginUser.UserID; operatorLog.AddTime = DateTime.Now; ncBase.CurrentEntities.AddToOperatorLog(operatorLog); ncBase.CurrentEntities.SaveChanges(); return(Json(new { status = 0, msg = "密码重置成功, 新密码:" + passWord })); }
/// <summary> /// 用户注册 /// </summary> /// <param name="entity"></param> /// <returns>UserID大于0:成功 ,小于0:各种失败</returns> public virtual int addPublicUser(PublicUserModel entity) { string passWordAdorn = ConfigUtility.GetValue("PassWordAdorn"); DbCommand cmd = GetStoredProcCommand("P_Api_addPublicUser"); AddOutParameter(cmd, "@UserID", DbType.Int32, 4); AddInParameter(cmd, "@Name", DbType.String, entity.Name); AddInParameter(cmd, "@Password", DbType.String, StringUtility.ToMd5String(passWordAdorn + entity.Password)); AddInParameter(cmd, "@Portrait", DbType.String, entity.Portrait); AddInParameter(cmd, "@Molblie", DbType.String, entity.Molblie); AddInParameter(cmd, "@Tel", DbType.String, entity.Tel); AddInParameter(cmd, "@NickName", DbType.String, entity.NickName); AddInParameter(cmd, "@EnrolnName", DbType.String, entity.EnrolnName); AddInParameter(cmd, "@Sex", DbType.Int32, entity.Sex); AddInParameter(cmd, "@Address", DbType.String, entity.Address); AddInParameter(cmd, "@Email", DbType.String, entity.Email); AddInParameter(cmd, "@QQ", DbType.String, entity.QQ); AddInParameter(cmd, "@IP", DbType.String, entity.IP); AddInParameter(cmd, "@CityID", DbType.Int32, entity.CityID); AddInParameter(cmd, "@CompanyId", DbType.Int32, entity.CompanyId); AddInParameter(cmd, "@StoreId", DbType.Int32, entity.StoreId); AddInParameter(cmd, "@LastLoginIP", DbType.String, entity.LastLoginIP); AddInParameter(cmd, "@VipType", DbType.Int32, entity.VipType); AddInParameter(cmd, "@DistrictId", DbType.Int32, entity.DistrictId); AddInParameter(cmd, "@RegionId", DbType.Int32, entity.RegionId); AddInParameter(cmd, "@Points", DbType.Int32, 100); //初始赠送积分 AddInParameter(cmd, "@Remarks", DbType.String, entity.Remarks); ExecuteNonQuery(cmd); int outUserId = 0; int.TryParse(cmd.Parameters["@UserID"].Value.ToString(), out outUserId); return(outUserId); }
public static string PutFile(string bucket, string key, Stream stream) { try { var scope = bucket + ":" + key; var policy = new PutPolicy(scope); string upToken = policy.Token(); var extra = new PutExtra(); var client = new IOClient(); var ret = client.Put(upToken, key, stream, extra); if (ret.OK) { return(string.Format(ConfigUtility.GetValue("QiNiuDomain"), bucket) + ret.key); } else { return(""); } } catch (Exception e) { log4net.LogManager.GetLogger("ImageUpload").Error(e.Message); return(""); } }
public static string GrabPic(string imgUrl, bool isLocalHost = false) { string fileExt = string.Empty; string newUrl = imgUrl; byte[] buffer = Core.Utilities.HttpUtility.GetData(imgUrl, null, false); int extIndex = imgUrl.LastIndexOf("."); fileExt = imgUrl.Substring(extIndex, imgUrl.Length - extIndex); using (MemoryStream target = new MemoryStream(buffer)) { if (isLocalHost) { newUrl = QiniuService.PutFileStringStream(target, "WX", fileExt); } else { byte[] data = target.ToArray(); string md5 = ToMd5String(data); var path = @"Images\temp\"; var fullPath = AppDomain.CurrentDomain.BaseDirectory + path; if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } System.IO.File.WriteAllBytes(fullPath + md5 + fileExt, data); newUrl = ConfigUtility.GetValue("QiNiuDomain") + md5 + fileExt; } } return(newUrl); }
public ActionResult ReportNewsByLogId(string logId) { List <string> openids = ConfigUtility.GetValue("Report.OpenIdListForNews").Split(";".ToArray(), StringSplitOptions.RemoveEmptyEntries).ToList(); if (openids.Count == 0) { openids.Add("okW7twhyUaxwcPnKt93urudB40OI"); openids.Add("okW7twgxMor7gtphIQuJnS396KfI"); } var client = new MongoClient(ConfigUtility.GetValue("Report.NewsMongoDb") ?? "mongodb://192.168.0.173"); MongoDatabase NewsTempDatabase = client.GetServer().GetDatabase("Temp"); MongoCollection <BsonDocument> tempCollection = NewsTempDatabase.GetCollection <BsonDocument>("NewsCrawler"); MongoCollection <BsonDocument> logCollection = NewsTempDatabase.GetCollection("NewsCrawlerLog"); var log = logCollection.FindOne(Query.EQ("_id", new ObjectId(logId))); //var log = new BsonDocument // { // {"_id", logId}, // {"siteUrls",jobRule.siteUrl}, // {"host",IP + " ## " + hostName}, // {"jobRule", JsonConvert.SerializeObject(jobRule)}, // {"startTime", start_time}, // {"endTime", end_time}, // {"usedTime", usedTime}, // {"newsUrls", JsonConvert.SerializeObject(urls)}, // {"urlSum", urls.Count}, // {"newsCrawled", newsCrawled} // }; if (log != null) { string sitrUrls = log["siteUrls"].ToString(); string lastNewsTitle = log["lastNewsTitle"].ToString(); string newsCrawled = log["newsCrawled"].ToString(); var newsCrawler = tempCollection.FindOne(Query.EQ("_id", sitrUrls)); string siteName = newsCrawler["siteName"].ToString(); string cityId = newsCrawler["cityId"].ToString(); lastNewsTitle = lastNewsTitle ?? "速去查看详情"; if (cityId == "4")//厦门 { foreach (var openId in openids) { try { wxPublic.WxPushMessage(openId, "您好,您有一条新的新闻站点采集消息。" , keyword1: newsCrawled, keyword2: siteName , keyword3: DateTime.Now.ToString("yyyy-MM-dd HH:mm"), keyword4: "", url: "http://lpsjadmin.ZJB.com/LouBaNews/NewsIndex?newslogid=" + logId , temp: "o0lKqQvcBXTDDr6K3NZZRi0jd6dXTPhGmv_KTBCUW9A", remark: lastNewsTitle ); } catch (Exception) { //WX. } } } } return(Json(new { ok = 1 }, JsonRequestBehavior.AllowGet)); }
/// <summary> /// 修改密码 /// </summary> /// <param name="userId"></param> /// <param name="pwd"></param> /// <returns></returns> public virtual int UpdateUserPassword(int userId, string pwd) { string passWordAdorn = ConfigUtility.GetValue("PassWordAdorn"); DbCommand cmd = GetStoredProcCommand("P_Api_UserPasswordUpdate"); AddInParameter(cmd, "@userId", DbType.Int32, userId); AddInParameter(cmd, "@pwd", DbType.String, StringUtility.ToMd5String(passWordAdorn + pwd)); return(ExecuteNonQuery(cmd)); }
public JsonResult EditEmail(string email) { if (string.IsNullOrEmpty(email)) { return(Json(new { status = 1, msg = "邮箱不能为空" })); } PublicUser emailUser = ncBase.CurrentEntities.PublicUser.Where(u => u.Email == email).FirstOrDefault(); if (emailUser.IsNoNull()) { return(Json(new { status = 1, msg = "修改失败,该邮箱已被使用" })); } PublicUserModel user = this.GetLoginUser(); int userId = this.GetLoginUser().UserID; //#region 直接修改 //PublicUserModel user = this.GetLoginUser(); //int userId = this.GetLoginUser().UserID; //PublicUser loginUser = ncBase.CurrentEntities.PublicUser.Where(u => u.UserID == userId).FirstOrDefault(); //loginUser.Email = email; //ncBase.CurrentEntities.SaveChanges(); //#endregion #region 发送邮箱进行验证后,在验证页面进行修改 string md5Code = ZJB.Core.Utilities.StringUtility.ToMd5String(userId.ToString() + email + DateTime.Now.ToString()); EmailEditValidCode ValidRecord = ncBase.CurrentEntities.EmailEditValidCode.Where(e => e.UserId == userId).FirstOrDefault(); if (ValidRecord.IsNoNull()) { ValidRecord.NewEmail = email; ValidRecord.Status = 0; ValidRecord.AddTime = DateTime.Now; ValidRecord.Code = md5Code; ncBase.CurrentEntities.SaveChanges(); } else { EmailEditValidCode newValid = new EmailEditValidCode() { AddTime = DateTime.Now, Code = md5Code, NewEmail = email, Status = 0, UserId = userId, }; ncBase.CurrentEntities.EmailEditValidCode.AddObject(newValid); ncBase.CurrentEntities.SaveChanges(); } ZJB.Core.Utilities.EmailSender emailHelper = new EmailSender(); string title = "修改邮箱验证"; string url = "http://" + Request.Url.Host + "/User/DoChangeEmail" + "?validCode=" + md5Code; string updateUrl = "<a target='_blank' href=\"" + url + "\">前往修改</a>"; string content = string.Format(ConfigUtility.GetValue("ChangeEamilConent"), user.Name, updateUrl); SendEmail(title, content, email); #endregion return(Json(new { status = 0, msg = "邮箱验证已发送到您新的邮箱,请查收" })); }
public virtual int addPublicUserThirdInfo(int UserID, int AppID, string OpenID, string UnionID) { string passWordAdorn = ConfigUtility.GetValue("PassWordAdorn"); DbCommand cmd = GetSqlStringCommand("INSERT INTO PublicUserThirdInfo(UserID, AppID, OpenID, UnionID) VALUES(@UserID, @AppID, @OpenID, @UnionID)"); AddInParameter(cmd, "@UserID", DbType.Int32, UserID); AddInParameter(cmd, "@AppID", DbType.Int32, AppID); AddInParameter(cmd, "@OpenID", DbType.String, OpenID); AddInParameter(cmd, "@UnionID", DbType.String, UnionID); int isuccess = ExecuteNonQuery(cmd); return(isuccess); }
private async void Unbinding() { try { KeyValuePair <string, string>[] postData = new KeyValuePair <string, string> [1]; postData[0] = new KeyValuePair <string, string>("deviceUniqueId", UniqueIdUtility.GetUniqueId()); await HttpUtility.GetHttpResponse(ConfigUtility.GetValue("UnbindDeviceAPI"), postData); } catch (Exception ex) { } CheckBinding(); }
public ActionResult ReportNewsByLogIdTest(string message) { List <string> openids = ConfigUtility.GetValue("Report.OpenIdListForNews").Split(";".ToArray(), StringSplitOptions.RemoveEmptyEntries).ToList(); if (openids.Count == 0) { openids.Add("okW7twhyUaxwcPnKt93urudB40OI"); openids.Add("okW7twgxMor7gtphIQuJnS396KfI"); } wxPublic.WxPushMessage(openids.LastOrDefault(), "您好,您有一条新的新闻站点采集消息。" , keyword1: "0", keyword2: "" , keyword3: DateTime.Now.ToString("yyyy-MM-dd HH:mm"), keyword4: "", url: "http://lpsjadmin.ZJB.com/" , temp: "o0lKqQvcBXTDDr6K3NZZRi0jd6dXTPhGmv_KTBCUW9A", remark: message ?? "其它" ); return(Json(new { ok = 1 }, JsonRequestBehavior.AllowGet)); }
/// <summary> /// 发送邮件 /// </summary> /// <param name="title">邮件标题</param> /// <param name="content">邮件内容</param> /// <param name="fromto">发到哪</param> public void SendEmail(string title, string content, string fromto) { EmailSender emailSender = new EmailSender { MailFrom = ConfigUtility.GetValue("MailFrom"), EnableSsl = Convert.ToBoolean(ConfigUtility.GetValue("EnableSsl")), Port = Convert.ToInt32(ConfigUtility.GetValue("Port")), SmtpServer = ConfigUtility.GetValue("SmtpServer"), IsPlainText = false, MailTo = fromto, DisplayName = "房产盒子" }; emailSender.MailPriority = System.Net.Mail.MailPriority.Normal; emailSender.Send(title, content); }
public virtual PublicUserModel PublicUserAdminLogin(string loginName, string pwd, int isAddLog = 1) { string passWordAdorn = ConfigUtility.GetValue("PassWordAdorn"); DbCommand cmd = GetStoredProcCommand("P_Api_PublicUserAdminLogin"); AddInParameter(cmd, "@loginName", DbType.String, loginName); AddInParameter(cmd, "@ip", DbType.String, IpUtility.GetIp()); AddInParameter(cmd, "@pwd", DbType.String, StringUtility.ToMd5String(passWordAdorn + pwd)); AddInParameter(cmd, "@isAddLog", DbType.Int32, isAddLog); DataSet ds = ExecuteDataSet(cmd); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { return(BulidPublicUser(ds.Tables[0].Rows[0])); } return(null); }
public ActionResult ReportNewsByResult([System.Web.Http.FromBody] string content) { JObject datas = null; if (!string.IsNullOrEmpty(content)) { datas = JObject.Parse(content); } if (datas != null) { string cityId = datas["cityId"].ToString(); if (cityId == "4")//厦门 { List <string> openids = ConfigUtility.GetValue("Report.OpenIdListForNews").Split(";".ToArray(), StringSplitOptions.RemoveEmptyEntries).ToList(); if (openids.Count == 0) { openids.Add("okW7twhyUaxwcPnKt93urudB40OI"); openids.Add("okW7twgxMor7gtphIQuJnS396KfI"); } string lastNewsTitle = datas["lastNewsTitle"].ToString(); string lastNewsUrl = datas["lastNewsUrl"].ToString(); string newsCrawled = datas["newsCrawled"].ToString(); string siteName = datas["siteName"].ToString(); lastNewsTitle = lastNewsTitle ?? "速去查看详情"; foreach (var openId in openids) { try { wxPublic.WxPushMessage(openId, "您好,您有一条新的新闻站点采集消息。" , keyword1: newsCrawled, keyword2: siteName , keyword3: DateTime.Now.ToString("yyyy-MM-dd HH:mm"), keyword4: "", url: "http://lpsjadmin.ZJB.com/LouBaNews/NewsIndex" , temp: "o0lKqQvcBXTDDr6K3NZZRi0jd6dXTPhGmv_KTBCUW9A", remark: lastNewsTitle ); } catch (Exception) { //WX. } } } } return(Json(new { ok = 1 }, JsonRequestBehavior.AllowGet)); }
public virtual Credential PostLogin(string loginName, string password, int loginType, out int returnValue) { string passWordAdorn = ConfigUtility.GetValue("PassWordAdorn"); DbCommand cmd = GetStoredProcCommand("P_Client_Login"); AddInParameter(cmd, "LoginName", DbType.String, loginName); AddInParameter(cmd, "Password", DbType.String, StringUtility.ToMd5String(passWordAdorn + password)); AddInParameter(cmd, "Token", DbType.String, StringUtility.NewGuidString()); AddInParameter(cmd, "ExpirationDate", DbType.DateTime, DateTime.Now.AddMonths(6)); AddInParameter(cmd, "IP", DbType.String, IpUtility.GetIp()); AddInParameter(cmd, "LoginType", DbType.Int32, loginType); AddOutParameter(cmd, "@returnValue", DbType.Int32, 0); var ds = ExecuteDataSet(cmd); returnValue = GetOutputParameter <Int32>(cmd, "@ReturnValue"); if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0) { return(null); } return(BuildCredential(ds.Tables[0])); }
private async void Binding(object state) { try { string[] ownerAndDeviceName = (string[])state; KeyValuePair <string, string>[] postData = new KeyValuePair <string, string> [3]; postData[0] = new KeyValuePair <string, string>("deviceUniqueId", UniqueIdUtility.GetUniqueId()); postData[1] = new KeyValuePair <string, string>("userId", ownerAndDeviceName[0]); postData[2] = new KeyValuePair <string, string>("deviceName", ownerAndDeviceName[1]); string returnValue = await HttpUtility.GetHttpResponse(ConfigUtility.GetValue("BindDeviceAPI"), postData); if (returnValue == "1") { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { MessageDialog msg = new MessageDialog(string.Format(StringResource.Instance["UserNameNotExist"], ownerAndDeviceName[0])); msg.Title = StringResource.Instance["Error"]; await msg.ShowAsync(); }); } if (returnValue == "2") { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { MessageDialog msg = new MessageDialog(string.Format(StringResource.Instance["DeviceNameExisted"], ownerAndDeviceName[1])); msg.Title = StringResource.Instance["Error"]; await msg.ShowAsync(); }); } } catch (Exception ex) { } CheckBinding(); }
public Crawler Fetch() { var request = HttpWebRequest.Create(this.SourceUrl) as HttpWebRequest; using (var response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { State = "Url returns " + response.StatusCode + ", " + response.StatusDescription; return(this); } if (response.ContentType.IndexOf("image") == -1) { State = "Url is not an image"; return(this); } ServerUrl = PathFormatter.Format(Path.GetFileName(this.SourceUrl), Config.GetString("catcherPathFormat")); var savePath = Server.MapPath(ServerUrl); try { var stream = response.GetResponseStream(); var reader = new BinaryReader(stream); byte[] bytes; using (var ms = new MemoryStream()) { byte[] buffer = new byte[4096]; int count; while ((count = reader.Read(buffer, 0, buffer.Length)) != 0) { ms.Write(buffer, 0, count); } bytes = ms.ToArray(); } string md5 = ToMd5String(bytes); if (Request.Url.Host.Contains("localhost") || Request.UserHostAddress == "127.0.0.1") { string imgUrl = QiniuService.PutFile("WX", md5, bytes); ServerUrl = imgUrl; State = "SUCCESS"; } else { var path = @"Images\temp\"; var fullPath = AppDomain.CurrentDomain.BaseDirectory + path; if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } System.IO.File.WriteAllBytes(fullPath + md5 + ".jpg", bytes); ServerUrl = ConfigUtility.GetValue("QiNiuDomain") + md5 + ".jpg"; State = "SUCCESS"; } } catch (Exception e) { State = "抓取错误:" + e.Message; } return(this); } }
public async void Run(IBackgroundTaskInstance taskInstance) { BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); try { Geolocator geolocator = new Geolocator(); Geoposition position = await geolocator.GetGeopositionAsync(); ////////////////////////////////////////////////////////////////////////// #if DEBUG XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01); XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text"); toastTextElements[0].AppendChild(toastXml.CreateTextNode(position.Coordinate.Point.Position.Latitude + "|" + position.Coordinate.Point.Position.Longitude)); ToastNotification toastNotification = new ToastNotification(toastXml); ToastNotificationManager.CreateToastNotifier().Show(toastNotification); #endif ////////////////////////////////////////////////////////////////////////// ApplicationDataContainer settings = ApplicationData.Current.LocalSettings; LimitedQueue <GPSInfo> queue; if (settings.Values.ContainsKey("Queue") == true) { string queueString = (string)settings.Values["Queue"]; queue = SerializerUtility.Deserialize <LimitedQueue <GPSInfo> >(queueString); } else { queue = new LimitedQueue <GPSInfo>(20); } queue.Push(new GPSInfo() { Latitude = position.Coordinate.Point.Position.Latitude, Longitude = position.Coordinate.Point.Position.Longitude, PositionSource = position.Coordinate.PositionSource.ToString() }); try { string deviceUniqueId = UniqueIdUtility.GetUniqueId(); GPSInfo[] gpsInfoList = queue.Retrive(); string gpsInfoListJson = SerializerUtility.Serialize <GPSInfo[]>(gpsInfoList); KeyValuePair <string, string>[] postData = new KeyValuePair <string, string> [2]; postData[0] = new KeyValuePair <string, string>("deviceUniqueId", deviceUniqueId); postData[1] = new KeyValuePair <string, string>("gpsInfoList", gpsInfoListJson); await HttpUtility.GetHttpResponse(ConfigUtility.GetValue("SendPositionAPI"), postData); queue.Clear(); } finally { string queueString = SerializerUtility.Serialize <LimitedQueue <GPSInfo> >(queue); settings.Values["Queue"] = queueString; } } catch (Exception ex) { } deferral.Complete(); }
private async void CheckBinding() { try { KeyValuePair <string, string>[] postData = new KeyValuePair <string, string> [1]; postData[0] = new KeyValuePair <string, string>("deviceUniqueId", UniqueIdUtility.GetUniqueId()); string owner = await HttpUtility.GetHttpResponse(ConfigUtility.GetValue("GetDeviceOwnerAPI"), postData); if (owner == "") { BackgroundTaskUtility.UnregisterBackgroundTask("MyTask"); ApplicationDataContainer settings = ApplicationData.Current.LocalSettings; if (settings.Values.ContainsKey("Queue") == true) { settings.Values.Remove("Queue"); } } else { BackgroundTaskUtility.RegisterBackgroundTask("RuntimeComponent.TrackingTask", "MyTask", new TimeTrigger(15, false), null); } await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (owner == "") { ownerTextbox.Text = ""; ownerTextbox.IsEnabled = true; deviceNameTextbox.Text = ""; deviceNameTextbox.IsEnabled = true; bindButton.IsEnabled = true; unbindButton.IsEnabled = false; } else { string[] ownerAndDeviceName = SerializerUtility.Deserialize <string[]>(owner); ownerTextbox.Text = ownerAndDeviceName[0]; ownerTextbox.IsEnabled = false; deviceNameTextbox.Text = ownerAndDeviceName[1]; deviceNameTextbox.IsEnabled = false; bindButton.IsEnabled = false; unbindButton.IsEnabled = true; } bindingGrid.Visibility = Visibility.Visible; }); } catch (Exception ex) { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { bindingGrid.Visibility = Visibility.Collapsed; errorGrid.Visibility = Visibility.Visible; }); } finally { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { progressRing.IsActive = false; progressRing.Visibility = Visibility.Collapsed; }); } }
public ContentResult Add(FormCollection form) { string domain = ConfigUtility.GetValue("domain"); string imageType = form["imageType"]; //最大文件大小f int maxSize = 1000000; HttpPostedFileBase imgFile = Request.Files["file"]; if (imgFile == null) { return(Content("<script>document.domain='" + domain + "';parent.callback('" + imageType + "', '请选择文件。', null);</script>")); } String fileName = imgFile.FileName; String fileExt = Path.GetExtension(fileName); if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize) { return(Content("<script>parent.callback(''" + imageType + "'', '上传文件大小超过限制。', null);</script>")); } if (!exts.Contains(fileExt)) { return(Content("<script>parent.callback(''" + imageType + "'', '上传文件扩展名是不允许的扩展名。\n只允许" + (exts.Aggregate((a, b) => a + ", " + b)) + "格式', null);</script>")); } imgFile.InputStream.Position = 0; //if (Request.Url.Host.Contains("localhost") || Request.UserHostAddress == "127.0.0.1") //{ // using (Stream stream = imgFile.InputStream) // { // string imgUrl = QiniuService.PutFileStringStream(stream, "WX", fileExt); // return Content("<script>parent.callback(''" + imageType + "'', '" + imgUrl + "', null);</script>"); // } //} //imgFile.InputStream.Position = 0; //MemoryStream target = new MemoryStream(); //imgFile.InputStream.CopyTo(target); //byte[] data = target.ToArray(); //#region 水印 //int pos = 0; //if (form["wmPos"] != null && form["wmPos"].ToString() != "")///有设置水印 //{ // int.TryParse(form["wmPos"].ToString(), out pos); //} //if (pos > 0) //{ // if (form["wmUrl"] != null && form["wmUrl"].ToString() != "")///有水印图片 // { // string wmUrl = form["wmUrl"].ToString(); // string ioPath = this.HttpContext.Server.MapPath(wmUrl); // System.Drawing.Image image = System.Drawing.Image.FromStream(target); // if (image.Width < 300 || image.Height < 200) // { // return Content("<script>parent.alert(''" + imageType + "'', '添加水印时尺寸不能小于300*200!', null);</script>"); // } // else // { // if (!string.IsNullOrEmpty(wmUrl) && System.IO.File.Exists(ioPath)) // { // data = addWaterMark(image, ioPath, (WaterPositionMode)pos); // } // } // } //} //#endregion //string md5 = ToMd5String(data); //var path = @"Images\temp\"; //var fullPath = AppDomain.CurrentDomain.BaseDirectory + path; //if (!Directory.Exists(fullPath)) // Directory.CreateDirectory(fullPath); //System.IO.File.WriteAllBytes(fullPath + md5 + fileExt, data); //return Content("<script>parent.callback('" + imageType + "', '" // + ConfigUtility.GetValue("QiNiuDomain") + md5 + fileExt + "', null);</script>"); imgFile.InputStream.Position = 0; MemoryStream target = new MemoryStream(); imgFile.InputStream.CopyTo(target); byte[] data = target.ToArray(); #region 水印 int pos = 0; if (form["wmPos"] != null && form["wmPos"].ToString() != "")///有设置水印 { int.TryParse(form["wmPos"].ToString(), out pos); } if (pos > 0) { if (form["wmUrl"] != null && form["wmUrl"].ToString() != "")///有水印图片 { string wmUrl = form["wmUrl"].ToString(); string ioPath = this.HttpContext.Server.MapPath(wmUrl); System.Drawing.Image image = System.Drawing.Image.FromStream(target); if (image.Width < 300 || image.Height < 200) { return(Content("<script>parent.alert(''" + imageType + "'', '添加水印时尺寸不能小于300*200!', null);</script>")); } else { if (!string.IsNullOrEmpty(wmUrl) && System.IO.File.Exists(ioPath)) { data = addWaterMark(image, ioPath, (WaterPositionMode)pos); } } } } #endregion string md5 = ToMd5String(data); using (Stream stream = new MemoryStream(data)) { string imgUrl = QiniuService.PutFileStringStream(stream, "zhujia", fileExt); return(Content("<script>parent.callback(''" + imageType + "'', '" + imgUrl + "', null);</script>")); } }
public ActionResult GetPwd(String pwd) { string passWordAdorn = ConfigUtility.GetValue("PassWordAdorn"); return(Content(StringUtility.ToMd5String(passWordAdorn + pwd))); }
public override void Process() { byte[] uploadFileBytes = null; string uploadFileName = null; if (UploadConfig.Base64) { uploadFileName = UploadConfig.Base64Filename; uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]); } else { var file = Request.Files[UploadConfig.UploadFieldName]; uploadFileName = file.FileName; if (!CheckFileType(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); var localPath = Server.MapPath(savePath); try { //if (!Directory.Exists(Path.GetDirectoryName(localPath))) //{ // Directory.CreateDirectory(Path.GetDirectoryName(localPath)); //} //File.WriteAllBytes(localPath, uploadFileBytes); //Result.Url = savePath; //Result.State = UploadState.Success; string md5 = ToMd5String(uploadFileBytes); if (Request.Url.Host.Contains("localhost") || Request.UserHostAddress == "127.0.0.1") { string imgUrl = QiniuService.PutFile("WX", md5, uploadFileBytes); Result.Url = imgUrl; Result.State = UploadState.Success; } else { var path = @"Images\temp\"; var fullPath = AppDomain.CurrentDomain.BaseDirectory + path; if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } System.IO.File.WriteAllBytes(fullPath + md5 + ".jpg", uploadFileBytes); Result.Url = ConfigUtility.GetValue("QiNiuDomain") + md5 + ".jpg"; Result.State = UploadState.Success; } } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }
public ActionResult uploadimage(FormCollection form) { string domain = ConfigUtility.GetValue("domain"); //最大文件大小f int maxSize = 1000000; HttpPostedFileBase imgFile = Request.Files["photoimg"]; if (imgFile == null) { return(JsonReturnValue(new { Success = 0, imgurl = "", msg = "请选择文件" }, JsonRequestBehavior.AllowGet)); } String fileName = imgFile.FileName; String fileExt = Path.GetExtension(fileName); if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize) { return(JsonReturnValue(new { Success = 0, imgurl = "", msg = "上传文件大小超过限制" }, JsonRequestBehavior.AllowGet)); } if (!exts.Contains(fileExt)) { return(JsonReturnValue(new { Success = 0, imgurl = "", msg = "上传文件扩展名是不允许的扩展名。\n只允许" + (exts.Aggregate((a, b) => a + ", " + b)) + "格式" }, JsonRequestBehavior.AllowGet)); } imgFile.InputStream.Position = 0; imgFile.InputStream.Position = 0; MemoryStream target = new MemoryStream(); imgFile.InputStream.CopyTo(target); byte[] data = target.ToArray(); #region 水印 int pos = 0; if (form["wmPos"] != null && form["wmPos"].ToString() != "")//有设置水印 { int.TryParse(form["wmPos"].ToString(), out pos); } if (pos > 0) { if (form["wmUrl"] != null && form["wmUrl"].ToString() != "")//有水印图片 { string wmUrl = form["wmUrl"].ToString(); string ioPath = this.HttpContext.Server.MapPath(wmUrl); System.Drawing.Image image = System.Drawing.Image.FromStream(target); if (image.Width < 300 || image.Height < 200) { return(JsonReturnValue(new { Success = 0, imgurl = "", msg = "添加水印时尺寸不能小于300*200" }, JsonRequestBehavior.AllowGet)); } else { if (!string.IsNullOrEmpty(wmUrl) && System.IO.File.Exists(ioPath)) { data = addWaterMark(image, ioPath, (WaterPositionMode)pos); } } } } #endregion string md5 = ToMd5String(data); string imgUrl = QiniuService.PutFile("zhujia", md5 + fileExt, data); return(JsonReturnValue(new { Success = 0, imgurl = imgUrl, msg = "上传成功" }, JsonRequestBehavior.AllowGet)); }