protected override async Task <ResponseApi> AddMiddlewareExecuted(UserFileInfo obj) { base.GetBase64(obj); if (string.IsNullOrEmpty(obj.Base64)) { ResponseApi response1 = ResponseApi.Create(GetLanguage(), Code.UploadFileFail, false); return(await Task.FromResult(response1)); } obj = this.AddMiddlewareExecute(obj); var parent = base.UnitWork.FindSingle <UserFileInfo>(it => it.Base64 == obj.Base64); if (parent == null) { obj.Id = (int)base.UnitWork.Insert(obj); System.IO.File.WriteAllBytes($"{AddressConfig.UploadImgDirectory}\\{ obj.Src}", /*obj.Base64*/ Base64Helper.FromBase64String(obj.Base64)); obj = (UserFileInfo)obj.Clone(); } else { obj.Parent = parent; obj.Base64 = null; } obj.FileId = RandomHelper.OrderId.Sha1(); obj.Src = $"{RandomHelper.OrderId.Sha1()}.{obj.Parent.Src.Split('.').LastOrDefault()}"; obj.Id = (int)base.UnitWork.Insert(obj); var userFileEntry = this._userFileService.ToUserFileEntry(obj); this._userFileService.Publish(userFileEntry); ResponseApi response = ResponseApi.Create(GetLanguage(), Code.AddSuccess); response.Data = new { obj.Src, Id = obj.FileId }; return(await Task.FromResult(response)); }
/// <summary> /// 获取绝对路径 /// </summary> /// <param name="file"></param> /// <param name="nowPath"></param> /// <returns></returns> public static string FullPath(this UserFileInfo file, string nowPath = "") { if (file == null) { return(nowPath); } var currentNode = file.Path.IsNullOrEmpty() ? null : $"/{file.Path}"; var nodePath = nowPath.IsNullOrEmpty() ? null : $"/{nowPath}"; return(file == null ? nowPath : $"{file.Parent.FullPath()}{currentNode}{nodePath}"); }
private async Task UploadInner(UserFileInfo fileInfo, UserFile file, Stream sr, Guid uploadStatusId) { var uploadStatus = Stauts(); if (uploadStatusId != Guid.Empty) { var lastStatus = uploadStatus.FileStatus.Where(s => s.Id == uploadStatusId).FirstOrDefault(); if (lastStatus == null) { throw new ActionStatusMessageException(ActionStatusMessage.StaticMessage.CacheIsInvalid); } fileInfo = lastStatus.FileInfo; file = context.UserFiles.Find(uploadStatusId); } var f = new FileUploadStatus() { FileInfo = fileInfo, Total = fileInfo.Length, LastUpdate = DateTime.Now }; file.Data = new byte[fileInfo.Length]; uploadStatus.FileStatus.Add(f); await context.SaveChangesAsync().ConfigureAwait(true); try { while (f.Current < f.Total) { var bufSize = f.Total - upload_bufsize - f.Current > 0 ? upload_bufsize : f.Total - f.Current; await sr.ReadAsync(file.Data, (int)f.Current, (int)bufSize).ConfigureAwait(true); f.Current += bufSize; // 只有在时间达到10秒时才更新进度,减少服务器消耗 if (DateTime.Now.Subtract(f.LastUpdate).TotalSeconds > 10) { f.LastUpdate = DateTime.Now; context.FileUploadStatuses.Update(f); await context.SaveChangesAsync().ConfigureAwait(true); } } } catch (Exception ex) { Console.WriteLine($"UplloadInner.Exception:{ex.Message}"); } finally { context.UserFiles.Update(file); context.FileUploadStatuses.Update(f); await context.SaveChangesAsync().ConfigureAwait(true); } }
protected override async Task <ResponseApi> EditMiddlewareExecuted(UserFileInfo obj) { obj.UpdateDate = DateTime.Now; base.GetBase64(obj); this.EditMiddlewareExecute(obj); if (string.IsNullOrEmpty(obj.Base64)) { var oldObj = base.UnitWork.FindSingle <SocialContact.Domain.Core.UserFileInfo>(it => it.Id == obj.Id && it.FileId == obj.FileId); if (oldObj == null) { ResponseApi response1 = ResponseApi.Create(GetLanguage(), Code.UploadFileFail, false); return(await Task.FromResult(response1)); } oldObj.FileId = RandomHelper.OrderId.Sha1(); oldObj.Src = $"{RandomHelper.OrderId.Sha1()}.{oldObj.Src.Split('.').LastOrDefault()}"; obj.FileId = oldObj.FileId; obj.Src = oldObj.Src; obj.Parent = oldObj.Parent; base.UnitWork.Update <UserFileInfo>(it => it.Id == obj.Id, it => new UserFileInfo() { UpdateDate = DateTime.Now, Admin = obj.Admin, Category = obj.Category, Description = obj.Description, FileId = obj.FileId, Src = obj.Src }); } else { var parent = base.UnitWork.FindSingle <UserFileInfo>(it => it.Base64 == obj.Base64); if (parent == null) { parent = (UserFileInfo)obj.Clone(); parent.Parent = null; parent.Base64 = obj.Base64; parent.Id = (int)base.UnitWork.Insert(parent); System.IO.File.WriteAllBytes($"{AddressConfig.UploadImgDirectory}\\{ parent.Src}", Base64Helper.FromBase64String(parent.Base64)); } obj.Base64 = null; obj.Parent = parent; obj.FileId = RandomHelper.OrderId.Sha1(); obj.Src = $"{RandomHelper.OrderId.Sha1()}.{obj.Parent.Src.Split('.').LastOrDefault()}"; base.UnitWork.Update(obj); } var userFileEntry = this._userFileService.ToUserFileEntry(obj); this._userFileService.Publish(userFileEntry); ResponseApi response = ResponseApi.Create(GetLanguage(), Code.ModifySuccess); response.Data = new { obj.Src, Id = obj.FileId }; return(await Task.FromResult(response)); }
private void Upload(HttpContext context) { var result = OpResult.Denied; string jsonResult = serializer.Serialize(result); if (context.Request.Files.Count > 0) { fileUploaded = context.Request.Files[0]; try { if (OnFileUploading(path, fileUploaded, ref result)) { result = fileSystem.SaveFile(path, fileUploaded, overwriteExistingFiles); if (result == OpResult.Succeed) { jsonResult = serializer.Serialize( UserFileInfo.FromPostedFile(fileUploaded, Path.GetFileName(fileUploaded.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles)).ToJson()); } else { jsonResult = serializer.Serialize(result); } } } catch (Exception ex) { log.Error(ex); result = OpResult.Error; jsonResult = serializer.Serialize(result); } } else { // no file posted jsonResult = serializer.Serialize(OpResult.Error); } //this is supposed to be an html response not a json response context.Response.ContentType = "text/html"; Encoding encoding = new UTF8Encoding(); context.Response.ContentEncoding = encoding; context.Response.Write(BuildHtmlWrapper(context, jsonResult)); //RenderJsonResult(context, result); }
public UserFileInfo LoadFromCurrentPath(string filename, UserFileInfo current) { var result = context.UserFileInfos.AsQueryable(); if (current == null) { result = result.Where(c => c.Parent == null); } else { result = result.Where(c => c.Parent != null && c.Parent.Id == current.Id); } result = result.Where(c => c.Name == filename); return(result.FirstOrDefault()); }
/// <summary> /// 下载链接 /// </summary> /// <param name="file"></param> /// <param name="downloadType"></param> /// <returns></returns> public static string DownloadUrl(this UserFileInfo file, DownloadType downloadType = DownloadType.ByPath) { switch (downloadType) { case DownloadType.ByPath: return($"{fileDownloadPathByPath}?path={file.FullPath()}&filename={file?.Name}"); case DownloadType.ById: return($"{fileDownloadPathById}{file?.Id}"); case DownloadType.ByStatic: return($"{fileDownloadPathByStatic}{file?.Id}"); default: throw new ArgumentOutOfRangeException(nameof(downloadType)); } }
protected override async Task <ResponseApi> AddMiddlewareExecuted(AdminInfo obj) { obj = this.AddMiddlewareExecute(obj); var fileInfo = new UserFileInfo(); UserFileInfo adminHeadPic = null; base.GetBase64(fileInfo); if (string.IsNullOrEmpty(fileInfo.Base64)) { fileInfo.FileId = obj.HeadPic.FileId; adminHeadPic = base.UnitWork.FindSingle <UserFileInfo>(it => it.FileId == fileInfo.FileId && it.Type == "head_pic"); if (adminHeadPic == null) { return(await Task.FromResult(ResponseApi.Create(GetLanguage(), Code.UploadFileFail))); } adminHeadPic.FileId = RandomHelper.OrderId.Sha1(); adminHeadPic.Src = $"{RandomHelper.OrderId.Sha1()}.{adminHeadPic.Src.Split('.').LastOrDefault()}"; } else { var parent = base.UnitWork.FindSingle <UserFileInfo>(it => it.Base64 == fileInfo.Base64); if (parent == null) { fileInfo.Id = (int)base.UnitWork.Insert(fileInfo); System.IO.File.WriteAllBytes($"{AddressConfig.UploadImgDirectory}\\{ fileInfo.Src}", Base64Helper.FromBase64String(fileInfo.Base64)); parent = fileInfo; } adminHeadPic = (UserFileInfo)parent.Clone(); adminHeadPic.Id = (int)base.UnitWork.Insert(adminHeadPic); } obj = this.AddMiddlewareExecute(obj); var userFileEntry = this._userFileService.ToUserFileEntry(adminHeadPic); this._userFileService.Publish(userFileEntry); obj.HeadPic = adminHeadPic; this.UnitWork.Insert(obj); this.UnitWork.Update <UserFileInfo>(it => it.Id == adminHeadPic.Id, it => new UserFileInfo() { Admin = obj, Type = "head_pic", FileId = adminHeadPic.FileId, Src = adminHeadPic.Src }); ResponseApi response = ResponseApi.Create(GetLanguage(), Code.AddSuccess); return(await Task.FromResult(response)); }
public bool Remove(UserFileInfo file) { if (file == null) { return(false); } var data = context.UserFiles.Where(f => f.Id == file.Id).FirstOrDefault(); if (data == null) { return(false); } data.Remove(); context.UserFiles.Update(data); file.Remove(); context.UserFileInfos.Update(file); context.SaveChanges(); return(true); }
public static FileInfoVDto ToVdto(this UserFileInfo model, FileInfoVDto raw = null) { if (model == null) { return(null); } if (raw == null) { raw = new FileInfoVDto(); } raw.Id = model.Id; raw.Create = model.Create; raw.IsRemoved = model.IsRemoved; raw.IsRemovedDate = model.IsRemovedDate; raw.FromClient = model.FromClient; raw.LastModify = model.LastModify; raw.Length = model.Length; raw.Name = model.Name; raw.Path = model.Path; return(raw); }
public UserFileInfo GetNode(string path, bool mkdWhenNotExist = false, UserFileInfo current = null) { if (path == null) { return(current); } var exactPath = path.Trim('/'); if (path.IsNullOrEmpty()) { return(null); } var list = current == null? context.UserFileInfosDb.Where(f => f.Parent == null) : context.UserFileInfosDb.Where(f => f.Parent != null).Where(f => f.Parent.Id == current.Id); var paths = exactPath.Split('/'); var next = list.Where(f => f.Path == paths[0]).FirstOrDefault(); if (next == null && mkdWhenNotExist) { next = new UserFileInfo() { Path = paths[0], Parent = current, Create = DateTime.Now, }; context.UserFileInfos.Add(next); context.SaveChanges(); } if (next == null) { return(null); } if (paths.Length > 1) { return(GetNode(exactPath.Substring(paths[0].Length + 1), mkdWhenNotExist, next)); } return(next); }
public async Task <string> GetFileInfo(string id) { if (string.IsNullOrEmpty(id)) { return(JsonConvert.SerializeObject(new RequestResult() { Flag = -1, Message = "参数错误" })); } try { ObjectId _id = new ObjectId(id); UserFiles userFile = await _userFiles.Find(Builders <UserFiles> .Filter.Eq(q => q.Id, _id)).FirstOrDefaultAsync(); Files file = await _files.Find(Builders <Files> .Filter.Eq(q => q.Id, userFile.FileID)).FirstOrDefaultAsync(); UserFileInfo userFileInfo = new UserFileInfo() { FileName = userFile.FileName, MD5 = file.MD5, Position = file.Position, State = file.State }; return(JsonConvert.SerializeObject(new RequestResult() { Flag = 1, Message = "新建文件成功", Data = userFileInfo })); } catch (Exception) { return(JsonConvert.SerializeObject(new RequestResult() { Flag = -2, Message = "查询文件失败" })); } }
protected override async Task <ResponseApi> EditMiddlewareExecuted(AdminInfo obj) { this.EditMiddlewareExecute(obj); obj.UpdateDate = DateTime.Now; var oldObj = UnitWork.FindSingle <AdminInfo>(it => it.Id == obj.Id); obj = UpdateOldObject(obj, ref oldObj); var fileInfo = obj.HeadPic ?? new UserFileInfo() { Admin = obj }; fileInfo.Admin = obj; UserFileInfo adminHeadPic = null; base.GetBase64(fileInfo); if (string.IsNullOrEmpty(fileInfo.Base64)) { adminHeadPic = base.UnitWork.FindSingle <SocialContact.Domain.Core.UserFileInfo>(it => it.Admin.Id == obj.Id && it.FileId == fileInfo.FileId && it.Type == "head_pic"); if (Request.Form.Files.Count == 0 && adminHeadPic == null) { return(await Task.FromResult(ResponseApi.Create(GetLanguage(), Code.UploadFileFail))); } adminHeadPic.FileId = RandomHelper.OrderId.Sha1(); adminHeadPic.Src = $"{RandomHelper.OrderId.Sha1()}.{adminHeadPic.Parent.Src.Split('.').LastOrDefault()}"; } else { adminHeadPic = base.UnitWork.FindSingle <SocialContact.Domain.Core.UserFileInfo>(it => it.Admin.Id == obj.Id && it.Type == "head_pic"); if (adminHeadPic == null) { return(await Task.FromResult(ResponseApi.Create(GetLanguage(), Code.UploadFileFail))); } if (adminHeadPic.Parent.Base64 != fileInfo.Base64) { var temp = base.UnitWork.FindSingle <SocialContact.Domain.Core.UserFileInfo>(it => it.Base64 == fileInfo.Base64); if (temp == null) { adminHeadPic.Parent.Id = (int)base.UnitWork.Insert(fileInfo); System.IO.File.WriteAllBytes($"{AddressConfig.UploadImgDirectory}\\{ fileInfo.Src}", Base64Helper.FromBase64String(fileInfo.Base64)); } else { adminHeadPic.Parent = temp; } } adminHeadPic.FileId = RandomHelper.OrderId.Sha1(); adminHeadPic.Src = $"{RandomHelper.OrderId.Sha1()}.{adminHeadPic.Parent.Src.Split('.').LastOrDefault()}"; base.UnitWork.Update <UserFileInfo>(it => it.Id == adminHeadPic.Id, it => new UserFileInfo() { Parent = adminHeadPic.Parent, FileId = adminHeadPic.FileId, Src = adminHeadPic.Src, UpdateDate = DateTime.Now }); } obj.HeadPic = adminHeadPic; var userFileEntry = this._userFileService.ToUserFileEntry(adminHeadPic); this._userFileService.Publish(userFileEntry); base.UnitWork.Update(obj); ResponseApi response = ResponseApi.Create(GetLanguage(), Code.ModifySuccess); return(await Task.FromResult(response)); }
private ApiResult GenerateQrCodeImg(QrCodeDataModel model, out UserFileInfo jpgFile, out UserFileInfo svgFile) { var fileNameRaw = $"{model.Data}_{model.Margin}_{model.Icon}_{model.LightColor}_{model.DarkColor}_{model.Size}"; var fileName = $"{fileNameRaw.ToMd5()}"; var imgFileName = $"{fileName}.jpg"; var svgFileName = $"{fileName}.svg"; UserFile iconFileRaw = null; if (model.Icon?.FileName != null) { Guid.TryParse(model.Icon.FileName, out var fid); if (fid != Guid.Empty) { iconFileRaw = _fileServices.Download(fid); } } Bitmap icon = null; if (iconFileRaw != null) { using (var iconMs = new MemoryStream(iconFileRaw.Data)) { icon = new Bitmap(iconMs); } } jpgFile = _fileServices.Load(QRCodePath, imgFileName); svgFile = _fileServices.Load(QRCodePath, svgFileName); if (jpgFile != null && svgFile != null) { return(null); } if (model == null) { return(ActionStatusMessage.StaticMessage.QrCode.NoData); } var rawText = model.Data; if (rawText == null) { return(ActionStatusMessage.StaticMessage.QrCode.NoData); } var qrCodeData = new QRCoder.QRCodeGenerator().CreateQrCode(rawText, QRCodeGenerator.ECCLevel.H); var svg = new SvgQRCode(qrCodeData).GetGraphic(model.Size, model.DarkColor, model.LightColor, true, SvgQRCode.SizingMode.ViewBoxAttribute); var bitmap = new QRCode(qrCodeData).GetGraphic(model.Size, ColorTranslator.FromHtml(model.DarkColor), ColorTranslator.FromHtml(model.LightColor), icon, model.Icon?.IconSize ?? 15, model.Icon?.BorderSize ?? 6, model?.Margin ?? false); if (jpgFile == null) { using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, ImageFormat.Jpeg); var imgf = new FormFile(stream, 0, stream.Length, imgFileName, imgFileName); jpgFile = _fileServices.Upload(imgf, QRCodePath, imgFileName, Guid.Empty, Guid.Empty).Result; } } if (svgFile == null) { using (var sr = new MemoryStream()) { sr.Write(Encoding.UTF8.GetBytes(svg)); var svgf = new FormFile(sr, 0, sr.Length, svgFileName, svgFileName); svgFile = _fileServices.Upload(svgf, QRCodePath, svgFileName, Guid.Empty, Guid.Empty).Result; } } return(null); }
UserFileInfo Set(UserFileInfo fileInfo, UserInfo user = null, bool add = true) { fileInfo.User = add?null: user; string str = base.RedisCache.GetHashValue("file", fileInfo.FileId); if (add) { str = str ?? throw new Exception("用户文件不存在"); } UserFileInfo parent = null; UserFileInfo pic = null; if (str != null) { string[] strs = str.Split('_'); int index = str.IndexOf("_"); fileInfo.Src = str.Substring(0, index); fileInfo.Type = str.Substring(index + 1); fileInfo.Base64 = Base64Helper.Base64String(System.IO.File.ReadAllBytes($"{AddressConfig.UploadImgDirectory}\\{fileInfo.Src}")); parent = base.UnitWork.FindSingle <UserFileInfo>(it => it.Base64 == fileInfo.Base64); if (!add) { //pic = base.UnitWork.FindSingle<UserFileInfo>(it => it.User.Id == user.Id && it.FileId == fileInfo.FileId && it.Type == fileInfo.Type); pic = base.UnitWork.FindSingle <UserFileInfo>(it => it.FileId == fileInfo.FileId && it.Type == fileInfo.Type); if (pic == null) { throw new Exception("用户文件不存在"); } } } else { // pic = base.UnitWork.FindSingle<UserFileInfo>(it => it.User.Id == user.Id && it.FileId == fileInfo.FileId); pic = base.UnitWork.FindSingle <UserFileInfo>(it => it.FileId == fileInfo.FileId); if (pic == null) { throw new Exception("用户文件不存在"); } parent = pic.Parent; } if (parent == null) { parent = fileInfo; parent.Id = (int)base.UnitWork.Insert(parent); if (add) { pic = (UserFileInfo)parent.Clone(); pic.Id = (int)base.UnitWork.Insert(pic); } } else { if (add) { pic = fileInfo; pic.Parent = parent; pic.Base64 = null; pic.Id = (int)base.UnitWork.Insert(pic); } } if (add) { var userFileEntry1 = this._userFileService.ToUserFileEntry(pic); this._userFileService.Publish(userFileEntry1); return(pic); } else { if (parent != null) { if (pic.Parent.Base64 != parent.Base64) { pic.Parent = parent; } } } pic.FileId = RandomHelper.OrderId.Sha1(); pic.Src = $"{RandomHelper.OrderId.Sha1()}.{pic.Parent.Src.Split('.').LastOrDefault()}"; base.UnitWork.Update <UserFileInfo>(it => it.Id == pic.Id, it => new UserFileInfo() { Parent = pic.Parent, FileId = pic.FileId, Src = pic.Src, UpdateDate = DateTime.Now }); var userFileEntry = this._userFileService.ToUserFileEntry(pic); this._userFileService.Publish(userFileEntry); return(pic); }
public async Task <UserFileInfo> Upload(IFormFile file, string path, string filename, Guid uploadStatusId, Guid clientKey) { if (file == null) { return(null); } UserFile f = null; UserFileInfo fi = null; filename = filename.IsNullOrEmpty() ? file.FileName : filename; var currentNode = GetNode(path, true, null); if (uploadStatusId == Guid.Empty) { // 判断文件是否已存在,若已存在则先删除 lock (fileLock) { fi = LoadFromCurrentPath(filename, currentNode); if (fi != null) { f = context.UserFiles.Where(st => st.Id == fi.Id).FirstOrDefault(); if (!fi.IsRemoved && fi.ClientKey != clientKey) { throw new ActionStatusMessageException(ActionStatusMessage.Account.Auth.Invalid.Default); } var uploadingFile = context.FileUploadStatuses.Where(st => st.FileInfo.Id == fi.Id).FirstOrDefault(); if (uploadingFile != null) { context.FileUploadStatuses.Remove(uploadingFile); } context.UserFileInfos.Remove(fi); context.SaveChanges(); } else { fi = new UserFileInfo() { Id = Guid.NewGuid(), Name = filename, Parent = currentNode, Path = null, Create = DateTime.Now, }; } if (f == null) { f = new UserFile() { Id = fi.Id }; context.UserFiles.Add(f); } fi.LastModify = DateTime.Now; fi.Length = file.Length; fi.FromClient = httpContext.HttpContext.Connection.RemoteIpAddress.ToString(); fi.ClientKey = clientKey == Guid.Empty ? Guid.NewGuid() : clientKey; fi.CreateBy = currentUserService?.CurrentUser; if (fi != null) { context.UserFileInfos.Add(fi); } // by serfend @ 202010092054 保存新的文件夹状态,防止多个文件夹被创建 context.SaveChanges(); } } using (var inputStream = file.OpenReadStream()) { await UploadInner(fi, f, inputStream, uploadStatusId).ConfigureAwait(true); } await context.SaveChangesAsync().ConfigureAwait(true); return(fi); }