public IActionResult UploadFormFile(IFormFile file) { if (file == null) { throw new HttpBadRequestException("请将Content-Type设置application/x-www-form-urlencoded,然后在formData的file附上图标文件"); } string iconExt = ""; Microsoft.Extensions.Primitives.StringValues headerVar; Request.Headers.TryGetValue("fileExt", out headerVar); if (headerVar.Count > 0) { iconExt = headerVar[0].Trim(); } if (string.IsNullOrWhiteSpace(iconExt)) { throw new HttpBadRequestException("请在Headers上添加fileExt标识icon的扩展名"); } iconExt = iconExt.Replace(".", string.Empty); //先把文件保存到临时文件夹,计算md5 var tmpPath = Path.Combine(tmpFileFolder, $"{Guid.NewGuid()}.{iconExt}"); using (FileStream fs = System.IO.File.Create(tmpPath)) { file.CopyTo(fs); // 清空缓冲区数据 fs.Flush(); } var md5 = MD5Gen.CalcFile(tmpPath); var fileName = $"{md5}.{iconExt}"; var iconPath = Path.Combine(iconFolder, fileName); //如果文件不存在资源文件夹,拷贝存储 if (!System.IO.File.Exists(iconPath)) { System.IO.File.Copy(tmpPath, iconPath); } //为文件生成缩略图标 ImageThumbnailCreator.SaveImageThumbnails(iconPath); //删除临时文件 if (System.IO.File.Exists(tmpPath)) { System.IO.File.Delete(tmpPath); } return(Ok($"/{OSSConst.AppRouteArea}/{OSSConst.IconFolder}/{fileName}")); }
/// <summary> /// 真实保存上传文件过程 /// </summary> /// <param name="saveFile"></param> /// <param name="owner"></param> /// <returns></returns> private async Task <IActionResult> SaveUpload(Action <string> saveFile, Account owner) { string fileState = ""; string fileExt = ""; string localPath = ""; string description = ""; Microsoft.Extensions.Primitives.StringValues headerVar; Request.Headers.TryGetValue("fileState", out headerVar); if (headerVar.Count > 0) { fileState = headerVar[0].Trim(); } Request.Headers.TryGetValue("fileExt", out headerVar); if (headerVar.Count > 0) { fileExt = headerVar[0].Trim(); } Request.Headers.TryGetValue("localPath", out headerVar); if (headerVar.Count > 0) { localPath = headerVar[0].Trim(); } Request.Headers.TryGetValue("description", out headerVar); if (headerVar.Count > 0) { description = headerVar[0].Trim(); } //几个头信息decode if (!string.IsNullOrWhiteSpace(fileState)) { fileState = System.Web.HttpUtility.UrlDecode(fileState); } if (!string.IsNullOrWhiteSpace(fileExt)) { fileExt = System.Web.HttpUtility.UrlDecode(fileExt); } if (!string.IsNullOrWhiteSpace(localPath)) { localPath = System.Web.HttpUtility.UrlDecode(localPath); } if (!string.IsNullOrWhiteSpace(description)) { description = System.Web.HttpUtility.UrlDecode(description); } //确保扩展名以 .开头,比如.jpg if (fileExt.Length > 0 && fileExt[0] != '.') { fileExt = "." + fileExt; } FileAsset res = new FileAsset(); res.Id = GuidGen.NewGUID(); //先生成临时ID,用于保存文件 res.Name = localPath.Length > 0 ? Path.GetFileName(localPath) : res.Id; res.Url = "/upload/" + res.Id; int fstate = 0; res.FileState = int.TryParse(fileState, out fstate) ? fstate : 0; res.FileExt = fileExt; res.LocalPath = localPath; res.Description = description; res.Creator = owner.Id; res.Modifier = owner.Id; res.OrganizationId = owner.OrganizationId; //保存 string savePath = Path.Combine(uploadPath, res.Id); try { saveFile(savePath); } catch { res.Id = ""; res.Url = ""; return(Ok(res)); } FileInfo fi = new FileInfo(savePath); res.Size = fi.Length; res.Md5 = Md5.CalcFile(savePath); //计算md5 res.Id = res.Md5; //将ID和url改为md5 res.Url = "/upload/" + res.Id + res.FileExt; string renamedPath = Path.Combine(uploadPath, res.Id + res.FileExt); //图片文件生成缩略图 var createThumbnails = new Action(() => { if (res.FileExt.Equals(".jpg", StringComparison.CurrentCultureIgnoreCase) || res.FileExt.Equals(".png", StringComparison.CurrentCultureIgnoreCase) || res.FileExt.Equals(".jpeg", StringComparison.CurrentCultureIgnoreCase) || res.FileExt.Equals(".gif", StringComparison.CurrentCultureIgnoreCase) || res.FileExt.Equals(".bmp", StringComparison.CurrentCultureIgnoreCase) ) { ImageThumbnailCreator.SaveImageThumbnails(renamedPath); } }); // 检查是否已经上传过此文件 var existRecord = await _Repository._DbContext.Set <FileAsset>().FindAsync(res.Id); if (existRecord != null) { // 数据库记录还在,但是文件不在了,重新保存下文件。 if (System.IO.File.Exists(renamedPath) == false) { //重命名文件 System.IO.File.Move(savePath, renamedPath); createThumbnails(); } else { //删除冗余文件 System.IO.File.Delete(savePath); } return(Ok(existRecord)); } else // 没有上传记录 { //没上传记录,但是已经有这个文件了,先删除已有的文件,使用用户的文件覆盖 if (System.IO.File.Exists(renamedPath)) { System.IO.File.Delete(renamedPath); } System.IO.File.Move(savePath, renamedPath); //重命名文件 createThumbnails(); } await _Repository.CreateAsync(owner.Id, res); //记录到数据库 return(Ok(res)); }