/// <summary> /// The convert if not exist. /// </summary> /// <param name="file"> /// The file. /// </param> /// <param name="ms"> /// The memory stream. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool ConvertIfNotExist(Domain.Entities.File file, byte[] ms = null) { var failedFolder = (string)System.IO.Path.Combine(FileModel.FileStoragePhysicalPath(this.settings), (string)this.settings.FailedPDFsFolder); var connectionString = (string)this.settings.ConnectionString; return(this.converter.ConvertIfNotExist(new FileDTO(file), failedFolder, connectionString, ms)); }
//[Produces("application/json")] //[Consumes("application/json", "multipart/form-data")] public async Task <IActionResult> Upload() { //var files = formfiles.Files; var files = Request.Form.Files; if (files == null || files.Count <= 0) { return(BadRequest(new StandardResult().Fail(StandardCode.LogicError, "文件不能为空"))); } if (files.Any(f => f.Length > FocusConstants.Misc.MaxUploadFileSize)) { return(Ok(new StandardResult().Fail(StandardCode.LogicError, string.Format("上传文件大小不能超过{0}MB", FocusConstants.Misc.MaxUploadFileSize / (1024 * 1024))))); } var fileSource = Enum.Parse <FileSource>(Request.Form["fileSource"].ToString()); var service = Ioc.Get <IFileService>(); if ((fileSource == FileSource.Article || fileSource == FileSource.Avatar) && !files.All(f => service.IsImage(f.FileName))) { return(BadRequest(new StandardResult().Fail(StandardCode.LogicError, "请选择图片上传"))); } var fileRootPath = AppSetting.FileRootPath + fileSource.GetDescriptionByName(); var fileId = Guid.NewGuid().ToString(); var fileName = service.GenerateFileName(Path.GetExtension(files[0].FileName), fileId); var fullPath = fileRootPath + "/" + fileName; if (!Directory.Exists(fileRootPath)) { Directory.CreateDirectory(fileRootPath); } var fileEntity = new Domain.Entities.File { Id = fileId, Name = fileName, Path = fullPath, Type = fileSource, CreatedBy = CurrentUserId, CreatedTime = DateTime.Now }; using (var stream = new FileStream(fileEntity.Path, FileMode.Create)) { await files[0].CopyToAsync(stream); } await service.UploadAsync(fileEntity); return(Ok(new StandardResult().Succeed("上传成功", AppSetting.ApiUrl + "/api/File/" + fileId))); }
public async Task <Domain.Entities.File> CreateFileAsync(string name, string filePath, int projectId) { var newFile = new Domain.Entities.File { Name = name, Uri = filePath, ProjectId = projectId }; context.File.Add(newFile); await context.SaveChangesAsync(); return(newFile); }
public async Task <IActionResult> UploadAvatarByBase64([FromBody] JObject data) { var imageBase64 = data["image"].ToObject <string>(); if (!string.IsNullOrWhiteSpace(imageBase64)) { var reg = new Regex("data:image/(.*);base64,"); imageBase64 = reg.Replace(imageBase64, ""); byte[] imageByte = Convert.FromBase64String(imageBase64); var fileRootPath = AppSetting.FileRootPath + FileSource.Avatar.GetDescriptionByName(); if (!Directory.Exists(fileRootPath)) { Directory.CreateDirectory(fileRootPath); } var fileService = Ioc.Get <IFileService>(); var fileId = Guid.NewGuid().ToString(); var fileName = fileService.GenerateFileName(".png", fileId); string fullPath = fileRootPath + "/" + fileName; using (var fileStream = new FileStream(fullPath, FileMode.Create)) { using (var memoryStream = new MemoryStream(imageByte)) { memoryStream.WriteTo(fileStream); } } var userService = Ioc.Get <IUserService>(); var user = await userService.GetUserById(CurrentUserId); var fileEntity = new Domain.Entities.File { Id = fileId, Name = fileName, Path = fullPath, Type = FileSource.Avatar, CreatedBy = CurrentUserId, CreatedTime = DateTime.Now }; user.Avatar = "/api/File/" + fileId; await fileService.UploadAvatarAsync(fileEntity, user); return(Ok(new StandardResult().Succeed("上传成功"))); } return(BadRequest(new StandardResult().Fail(StandardCode.LogicError, "请选择上传头像"))); }
public async Task <IActionResult> PostAsync(IFormFile formFile) { try { Domain.Entities.File file = new Domain.Entities.File(); using (var memoryStream = new MemoryStream()) { await formFile.CopyToAsync(memoryStream); // Upload the file if less than 5 MB int sizeLimitInMB = 5; if (memoryStream.Length < sizeLimitInMB * 1024 * 1024 && formFile.FileName.ToLower().EndsWith(".zip")) { file = new Domain.Entities.File() { Content = memoryStream.ToArray(), Name = formFile.FileName }; facade.Insert(file); } else { ModelState.AddModelError("File", "The file is too large."); } } return(new ObjectResult(file.Id)); } catch (ArgumentNullException ex) { return(NotFound(ex)); } catch (Exception ex) { return(BadRequest(ex)); } }
public bool ConvertIfNotExist(Domain.Entities.File file, string failedFolder, string connectionString, byte[] ms = null) { return(ConvertIfNotExist(new FileDTO(file), failedFolder, connectionString, ms)); }
public async Task <bool> Delete([FromBody] Domain.Entities.File file) { return(await _showService.DeleteFile(file)); }
public async Task <bool> Copy([FromBody] Domain.Entities.File file) { return(await _showService.CopyFile(file)); }
public async Task <CreateFileResponse> Handle(CreateFileRequest request, CancellationToken cancellationToken) { // create or update var result = new CreateFileResponse(); var options = _configuration.GetSection(SiUpinOptions.RootSection).Get <SiUpinOptions>(); var file = request.Files; if (file.Length > 0 && !string.IsNullOrEmpty(request.EntityID)) { var originalFileName = WebUtility.HtmlEncode(file.FileName); var existingFile = await _context.Files.FirstOrDefaultAsync(x => x.EntityID == request.EntityID, cancellationToken); if (existingFile == null) { // save file to directory var processFileResult = await _fileService.ProcessFile(file); if (processFileResult.IsSuccessful) { string folderPath; if (options.Environment == "Linux") { folderPath = Path.Combine(".", "SiUpinFiles", "Pictures"); } else { folderPath = Path.Combine("D:", "SiUpinFiles", "Pictures"); } var trustedFileNameForFileStorage = $"{originalFileName}"; var saveDocumentResult = await _fileService.SaveFile(processFileResult.FileContent, folderPath, trustedFileNameForFileStorage); if (!saveDocumentResult.IsSuccessful) { throw new Exception("Maaf ada kesalahan pada proses simpan File"); } } else { throw new Exception($"{processFileResult.ErrorMessage}"); } // save file to db var entity = new Domain.Entities.File { EntityID = request.EntityID, EntityType = request.EntityType, Name = originalFileName }; await _context.Files.AddAsync(entity); } else { string folderPath; if (options.Environment == "Linux") { folderPath = Path.Combine(".", "SiUpinFiles", "Pictures"); } else { folderPath = Path.Combine("D:", "SiUpinFiles", "Pictures"); } // remove existing file var removeDocumentResult = await _fileService.RemoveFile(folderPath, existingFile.Name); // save new file to directory var processFileResult = await _fileService.ProcessFile(file); if (processFileResult.IsSuccessful) { if (options.Environment == "Linux") { folderPath = Path.Combine(".", "SiUpinFiles", "Pictures"); } else { folderPath = Path.Combine("D:", "SiUpinFiles", "Pictures"); } var trustedFileNameForFileStorage = $"{originalFileName}"; var saveDocumentResult = await _fileService.SaveFile(processFileResult.FileContent, folderPath, trustedFileNameForFileStorage); if (!saveDocumentResult.IsSuccessful) { throw new Exception("Maaf ada kesalahan pada proses simpan File"); } } else { throw new Exception($"{processFileResult.ErrorMessage}"); } // update file name to database existingFile.Name = originalFileName; } await _context.SaveChangesAsync(cancellationToken); } return(result); }