public string UploadFileSingle(IFormFile file, string userId) { Random rnd = new Random(); string extension = Path.GetExtension(file.FileName); int num = rnd.Next(5000, 1000000); var filename = userId + DateTime.Now.ToString("yyyyMMddHHmmss") + num.ToString() + extension; return(QiniuHelper.UploadFile(file.OpenReadStream(), filename, QiniuConfig.AK, QiniuConfig.SK, QiniuConfig.Bucket)); }
public async Task <IActionResult> UpContentImg(IFormFile imgFile) { var res = await QiniuHelper.UploadStreamAsync(imgFile); if (res.Key != 200) { return(Json(new { errno = res.Key.ToString(), data = new string[] { res.Value } })); } return(Json(new { errno = "0", data = new string[] { res.Value } })); }
/// <summary> /// 删除事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnDelete_Click(object sender, EventArgs e) { var guids = FormHelper.GetRepeaterSelectedRowId(rptList); var imageKeys = FormHelper.GetRepeaterSelectedRowId(rptList, "GuId", "hfImageKey"); CategoryBll.DeleteByGuIds(guids); //七牛批量删除 QiniuHelper.DeleteDatas(imageKeys); BindData(); }
public ActionResult GetToken() { try { return(Json(new { uptoken = QiniuHelper.GetToken() }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { LogManager.GetCurrentClassLogger().Error(ex); return(null); } }
public ActionResult GetUploadToken() { string token = QiniuHelper.GetUploadToken(); return(Json(new { FileConfig.AccessKey, FileConfig.SecretKey, FileConfig.Bucket, Token = token }, JsonRequestBehavior.AllowGet)); }
public ActionResult RealDelArchive(int id) { //1.0 删除文章 (外键评论也会被删除) int val1 = articleService.Delete(id);//直接用自己写好的方法进行删除失败的原因是dbContext 乱了。。。垃圾框架! if (val1 == 1) { var fileList = fileService.GetDataListBy(f => f.FromArticleId == id); List <string> FilePathList = new List <string>();//暂存将被删的文件路径;用于删完文件表后再删七牛数据 //2.0 删除文件表 if (fileList.Count != 0 && fileList != null) { foreach (var file in fileList) { FilePathList.Add(file.FileOnLineURL); } int totalFile = 0; foreach (var file in fileList) { //2.0 删除文件表 int val2 = fileService.Delete(file.Id); if (val2 == 1) { totalFile += 1; } } //3.0 删七牛文件 if (totalFile == fileList.Count) { foreach (string path in FilePathList) { string bucket = ConfigurationManager.AppSettings["QiNiuURL"]; string key = path; bool flag = QiniuHelper.DeleteFile(bucket, key); } } } //2.0 删除索引以及返回jsoon InvertedIndex.IndexManager.Delete(id); return(Json(val1)); } else { return(Json(0)); } }
private UploadResult GetResult(byte[] uploadFileBytes) { var ret = QiniuHelper.GetResult(uploadFileBytes); if (ret.OK) { Result.Url = QiniuHelper.GetUrl(ret.key);; Result.key = ret.key; Result.State = UploadState.Success; } return(Result); }
//[EpcAuth] public async Task <ActionResult> Upload(string only_qiniu) { return(await RunActionAsync(async() => { if ((this.X.context.Request.Files?.Count ?? 0) <= 0) { return GetJsonRes("请选择要上传的文件"); } var file = this.X.context.Request.Files[0] ?? throw new ArgumentNullException("文件不存在"); if (file.ContentLength > Com.MbToB(1)) { return GetJsonRes("文件过大"); } var qiniu = new QiniuHelper(); if ((only_qiniu ?? "false").ToBool()) { var url = qiniu.Upload(file.GetBytes(), Com.GetUUID()); return GetJson(new _() { success = true, data = url }); } else { var path = Server.MapPath("~/static/upload/"); var uploader = new FileUpload() { MaxSize = Com.MbToB(1) }; var res = uploader.UploadSingleFile(file, path); if (!res.SuccessUpload) { return GetJsonRes("上传失败"); } var url = qiniu.Upload(res.FilePath, Com.GetUUID()); await Task.FromResult(1); return GetJson(new _() { success = true, data = url }); } })); }
/// <summary> /// 现在是一天 备份一次数据库 /// </summary> public void UpDbToQiniu() { #region 七牛 string qiniuak = ConfigHelper.GetConfigToString("qiniuak"); string qiniusk = ConfigHelper.GetConfigToString("qiniusk"); string qiniubk = ConfigHelper.GetConfigToString("qiniubk"); string a = ConfigHelper.GetConfigToString("backuppath"); string path = Path.Combine(a, $"blogdb{DateTime.Now.ToString("yyyyMMdd")}.sql"); HttpResult res = QiniuHelper.UpFile(path, qiniuak, qiniusk, qiniubk, "blogdb", 0); if (res.Code != 200) { LogHelper.WriteLog("上传失败" + res.SerializeObject()); } #endregion }
/// <summary> /// 删除文件 /// </summary> /// <param name="fid"></param> /// <param name="uid"></param> /// <returns></returns> public string DeleteFile(string fid, string uid) { var dal = new UpFileDal(); var model = dal.GetFirst(x => x.UID == fid && x.UserID == uid); if (model == null) { return("数据不存在"); } var md5 = model.FileMD5; if (dal.Delete(model) > 0) { if (!dal.Exist(x => x.FileMD5 == md5)) { QiniuHelper.Delete(md5); } } return("删除失败"); }
protected void Application_Start() { log4net.Config.XmlConfigurator.Configure( new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\log4net.config") ); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); //初始化七牛Key QiniuHelper.SetKey(); //之后不用再初始化 //启动Lucene索引处理任务 InvertedIndex.IndexManager.Start(); //执行搜索热词统计任务 QuartzTick.StartJob(); //10分钟执行一次 }
public ActionResult FileUploadAction() { return(RunActionWhenLogin((loginuser) => { string SavePath = Server.MapPath("~/static/upload/link_images/"); var uploader = new FileUpload() { AllowFileType = new string[] { ".gif", ".png", ".jpg", ".jpeg", ".bmp" }, }; var file = this.X.context.Request.Files["file"]; if (file != null) { var model = uploader.UploadSingleFile(file, SavePath); var path = model.FilePath; if (model.SuccessUpload && System.IO.File.Exists(path)) { try { var url = QiniuHelper.Upload(path, Com.GetUUID()); ViewData["img_url"] = url; //删除本地 System.IO.File.Delete(path); } catch (Exception e) { e.SaveLog(this.GetType()); ViewData["info"] = "上传到七牛错误"; } } else { ViewData["info"] = model.Info; } } return View(); })); }
//[HttpPost] public ActionResult GetQiniuToken() { var upToken = QiniuHelper.GetToken(); return(Json(new { uptoken = upToken }, JsonRequestBehavior.AllowGet)); }
public ActionResult qiniu() { var data = QiniuHelper.FindEntry("fas"); return(Content("")); }
public void qiniutest() { var x = QiniuHelper.FindEntry("fads"); }
public ActionResult UploadHeadIcon() { string bucket = ConfigurationManager.AppSettings["QiNiuBucket"]; //七牛空间 string localPath = "~/Content/images/tempicon/"; //本地文件绝对路径 string qiniuPath = ConfigurationManager.AppSettings["PathOfHeadIcon"]; //七牛路径 "headicon/日期/" qiniuPath += "/" + DateTime.Now.ToString("yyyyMMdd") + "/"; //七牛路径 headicon/ string fileType = ".jpg,.jpeg,.png,.gif"; int maxSize = 5; //开始上传 HttpPostedFileBase file = Request.Files[0]; if (file != null) { List <string> extList = fileType.Split(',').ToList(); var extension = Path.GetExtension(file.FileName); //后缀 if (extension != null && extList.Contains(extension.ToLower())) { string extendName = extension.ToLower(); //小写后缀名 int length = file.ContentLength; //文件大小 if (length > maxSize * 1024 * 1024) { //上传失败 string warning = "文件不得大于" + maxSize + "MB"; return(Content("<script>window.parent.uploadSuccess('" + warning + "| ');</script>")); } else { if (!Directory.Exists(localPath)) //创建目录 { Directory.CreateDirectory(Server.MapPath(localPath)); } localPath += file.FileName; file.SaveAs(Server.MapPath(localPath)); //先 保存文件 到本地 string qiniufileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + extendName; //上传至七牛 qiniuPath += qiniufileName; //日期/文件名 bool uploadflag = QiniuHelper.UploadFile(bucket, qiniuPath, Server.MapPath(localPath)); if (uploadflag) { //先删除本地临时图片 System.IO.File.Delete(Server.MapPath(localPath)); string qiniuUrlIndex = ConfigurationManager.AppSettings["QiNiuURL"]; HeadIcon icon = new HeadIcon() { IconName = qiniufileName, //现文件名 IconRawName = file.FileName, //原文件名 IconURL = qiniuUrlIndex + "/" + qiniuPath, Status = 1, UploadTime = DateTime.Now }; //入库 int val = iconService.Add(icon); if (val == 1) { return(Content("<script>window.parent.uploadSuccess('上传成功!|" + icon.IconURL + "');</script>")); } else { return(Content("<script>window.parent.uploadSuccess('上传至七牛成功,但入库时失败!|" + icon.IconURL + "');</script>")); } } else { string warning = "上传至七牛失败"; return(Content("<script>window.parent.uploadSuccess('" + warning + "| ');</script>")); } } } else { string warning = "图片格式不对"; return(Content("<script>window.parent.uploadSuccess('" + warning + "| ');</script>")); } } else { string warning = "还没选择文件"; return(Content("<script>window.parent.uploadSuccess('" + warning + "| ');</script>")); } }
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 { #region 再需要储存文件到服务器 //if (!Directory.Exists(Path.GetDirectoryName(localPath))) //{ // Directory.CreateDirectory(Path.GetDirectoryName(localPath)); //} //File.WriteAllBytes(localPath, uploadFileBytes); //Result.Url = savePath; //Result.State = UploadState.Success; #endregion #region 文件到七牛 var ret = QiniuHelper.GetResult(uploadFileBytes); if (ret.OK) { Result.Url = QiniuHelper.GetUrl(ret.key); Result.State = UploadState.Success; } #endregion } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }
/// <summary> /// 保存事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void BtnSave_OnClick(object sender, EventArgs e) { var imageFile = GetImage(); if (string.IsNullOrEmpty(StrGuid)) { var info = new CategoryInfo(); info.Name = tbName.Text; info.OrderId = ConvertHelper.GetInt(tbOrderId.Text); info.ParentGuid = ddlParentCategory.SelectedValue; var user = HttpContext.Current.Session["UserInfo"] as UserInfo; if (user != null) { info.UserGuid = user.Guid; } var blog = HttpContext.Current.Session["BlogInfo"] as BlogInfo; if (blog != null) { info.BlogGuid = blog.Guid; } if (imageFile != null) { var ret = QiniuHelper.GetResult(imageFile); if (ret.OK) { info.ImageUrl = QiniuHelper.GetUrl(ret.key); info.ImageKey = ret.key; } else { ScriptHelper.Alert("图片上传失败"); } } CategoryBll.Add(info); } else { var info = CategoryBll.GetModel(StrGuid); info.Name = tbName.Text; info.OrderId = ConvertHelper.GetInt(tbOrderId.Text); info.ParentGuid = ddlParentCategory.SelectedValue; if (imageFile != null) { var ret = QiniuHelper.GetResult(imageFile); if (ret.OK) { info.ImageUrl = QiniuHelper.GetUrl(ret.key); info.ImageKey = ret.key; } else { ScriptHelper.Alert("图片上传失败"); } } CategoryBll.Update(info); } Response.Redirect("CategoryList.aspx"); }
public IHttpActionResult getMapData(string callback = "") { var root = System.Web.HttpContext.Current.Server.MapPath("~/"); var version = db.systemInfos.Find("dataVer"); if (version == null) { return(Json(-1, "找不到版本配置信息")); } if (!File.Exists(root + "map_" + version.value + ".json")) { AssetManage.LoadDatabase(version.value); var map = new MapData(); //map.eventQuests = AssetManage.Database.mstEventQuest; map.events = AssetManage.Database.mstEvent; map.questGroups = AssetManage.Database.mstQuestGroup; //map.messions = AssetManage.Database.mstMission; map.svtGroups = AssetManage.Database.mstSvtGroup; map.wars = new List <War>(); Mapper.Initialize((config) => { config.CreateMap <mstWar, War>(); config.CreateMap <mstQuest, Quest>(); config.CreateMap <mstSpot, Spot>(); config.CreateMap <mstSpotRoad, SpotRoad>(); }); AutoMapper.Mapper.Map(AssetManage.Database.mstWar, map.wars); foreach (var war in map.wars) { war.spots = new List <Spot>(); foreach (var spot in AssetManage.Database.mstSpot) { if (spot.warId == war.id) { var nspot = Mapper.Map <mstSpot, Spot>(spot); war.spots.Add(nspot); nspot.quests = new List <Quest>(); foreach (var quest in AssetManage.Database.mstQuest) { if (quest.spotId == spot.id) { var nquest = Mapper.Map <mstQuest, Quest>(quest); nspot.quests.Add(nquest); nquest.phases = new List <mstQuestPhase>(); nquest.releases = new List <mstQuestRelease>(); foreach (var phase in AssetManage.Database.mstQuestPhase) { if (phase.questId == quest.id) { nquest.phases.Add(phase); } } foreach (var release in AssetManage.Database.mstQuestRelease) { if (release.questId == quest.id) { nquest.releases.Add(release); } } } } } } war.spotRoads = new List <SpotRoad>(); foreach (var spotRoad in AssetManage.Database.mstSpotRoad) { if (spotRoad.warId == war.id) { war.spotRoads.Add(Mapper.Map <mstSpotRoad, SpotRoad>(spotRoad)); } } } File.WriteAllText(root + "map_" + version.value + ".json", JsonConvert.SerializeObject(map)); QiniuHelper.Upload("map_" + version.value + ".json", root + "map_" + version.value + ".json"); } var url = "http://oj3vd47gp.bkt.clouddn.com/map_" + version.value + ".json"; return(Redirect(url)); }
public string UploadFileAfterCheckRepeat(FileInfo file, string uid, ref string file_url, ref string file_name, bool DeleteFileAfterUploadToQiniu = true) { try { if (!file.Exists) { throw new Exception("无法在磁盘上找到文件"); } var dal = new UpFileDal(); var dbmodel = new UpFileModel(); dbmodel.UserID = uid; dbmodel.FileName = file.Name; dbmodel.FileExt = file.Extension; dbmodel.FileSize = (int)file.Length; dbmodel.FilePath = file.FullName; dbmodel.CreateTime = DateTime.Now; //获取文件md5值 dbmodel.FileMD5 = SecureHelper.GetFileMD5(dbmodel.FilePath); if (!ValidateHelper.IsPlumpString(dbmodel.FileMD5)) { throw new Exception("获取文件MD5失败"); } //判断文件是否存在于七牛 var qiniu_file = QiniuHelper.FindEntry(dbmodel.FileMD5); bool FindInQiniu = qiniu_file.HasFile(); bool uploadToQiniuByMe = false; if (FindInQiniu) { //直接拿七牛中的文件地址 dbmodel.FileUrl = QiniuHelper.GetUrl(dbmodel.FileMD5); } else { var url = QiniuHelper.Upload(file.FullName, dbmodel.FileMD5); dbmodel.FileUrl = url; //标记文件是我上传到七牛的 uploadToQiniuByMe = true; } //运行到这里,七牛已经有文件了 //判断是否要添加到数据库 var res = AddFile(dbmodel); if (ValidateHelper.IsPlumpString(res)) { //如果是我上传到七牛的并且保存本地数据库失败就删除 if (uploadToQiniuByMe) { QiniuHelper.Delete(dbmodel.FileMD5); } return("保存到数据库失败"); } file_name = dbmodel.FileName; file_url = dbmodel.FileUrl; return(SUCCESS); } catch (Exception e) { throw e; } finally { if (DeleteFileAfterUploadToQiniu) { file.Delete(); } } }
/// <summary> /// 保存事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void BtnSave_OnClick(object sender, EventArgs e) { var imageFile = GetImage(); if (imageFile != null) { if (string.IsNullOrEmpty(StrGuid)) { var info = new PhotoInfo(); var ret = QiniuHelper.GetResult(imageFile); if (ret.OK) { info.ImageUrl = QiniuHelper.GetUrl(ret.key); info.ImageKey = ret.key; info.Name = tbName.Text; info.Tag = tbTag.Text; info.IsCover = chkCover.Checked; var user = HttpContext.Current.Session["UserInfo"] as UserInfo; if (user != null) { info.UserGuid = user.Guid; } info.Createtime = DateTime.Now; info.AlbumGuid = AlbumGuid; PhotoBll.Add(info); ScriptHelper.AlertAndRedirect("添加成功", "PhotoList.aspx?albumguid=" + AlbumGuid); } else { Util.ScriptHelper.Alert2("上传失败"); } } else { var info = PhotoBll.GetModel(StrGuid); var ret = QiniuHelper.GetResult(imageFile); if (ret.OK) { QiniuHelper.DeleteData(info.ImageKey); info.ImageUrl = QiniuHelper.GetUrl(ret.key); info.ImageKey = ret.key; info.Name = tbName.Text; info.Tag = tbTag.Text; info.IsCover = chkCover.Checked; var user = HttpContext.Current.Session["UserInfo"] as UserInfo; if (user != null) { info.UserGuid = user.Guid; } info.Createtime = DateTime.Now; info.AlbumGuid = AlbumGuid; PhotoBll.Update(info); ScriptHelper.AlertAndRedirect("修改成功", "PhotoList.aspx?albumguid=" + AlbumGuid); } else { Util.ScriptHelper.Alert2("上传失败"); } } } else { if (string.IsNullOrEmpty(StrGuid)) { Util.ScriptHelper.Alert2("没有文件"); } else { var info = PhotoBll.GetModel(StrGuid); info.Name = tbName.Text; info.Tag = tbTag.Text; info.IsCover = chkCover.Checked; PhotoBll.Update(info); ScriptHelper.AlertAndRedirect("修改信息成功", "PhotoList.aspx?albumguid=" + AlbumGuid); } } }