public async Task <IActionResult> UploadFile(UploadFileAddressModel model) { var conversation = await _dbContext.Conversations.SingleOrDefaultAsync(t => t.Id == model.ConversationId); if (conversation == null) { return(this.Protocol(ErrorType.NotFound, $"Could not find the target conversation with id: {model.ConversationId}!")); } var user = await GetKahlaUser(); if (!await _dbContext.VerifyJoined(user.Id, conversation)) { return(this.Protocol(ErrorType.Unauthorized, $"You are not authorized to upload file to conversation: {conversation.Id}!")); } var file = Request.Form.Files.First(); var path = $"conversation-{conversation.Id}/{DateTime.UtcNow.ToString("yyyy-MM-dd")}"; var savedFile = await _storageService.SaveToProbe(file, _configuration["UserFilesSiteName"], path, SaveFileOptions.SourceName); return(Json(new UploadFileViewModel { Code = ErrorType.Success, Message = "Successfully uploaded your file!", FilePath = $"{savedFile.SiteName}/{savedFile.FilePath}", FileSize = file.Length })); }
public async Task <JsonResult> UploadFile(UploadFileAddressModel model) { var app = await _coreApiService.ValidateAccessTokenAsync(model.AccessToken); //try find the target bucket var targetBucket = await _dbContext.Bucket.FindAsync(model.BucketId); if (targetBucket == null || targetBucket.BelongingAppId != app.AppId) { return(this.Protocal(ErrorType.Unauthorized, "The bucket you try to upload is not your app's bucket!")); } //try get the file from form var file = Request.Form.Files.First(); var newFile = new OSSFile { RealFileName = Path.GetFileName(file.FileName.Replace(" ", "")), FileExtension = Path.GetExtension(file.FileName), BucketId = targetBucket.BucketId, AliveDays = model.AliveDays, UploadTime = DateTime.Now }; //Ensure there not exists file with the same file name. lock (_obj) { var exists = _dbContext.OSSFile.Exists(t => t.RealFileName == newFile.RealFileName && t.BucketId == newFile.BucketId); if (exists) { return(this.Protocal(ErrorType.HasDoneAlready, "There already exists a file with that name.")); } //Save to database _dbContext.OSSFile.Add(newFile); _dbContext.SaveChanges(); } //Try saving file. string DirectoryPath = _configuration["StoragePath"] + $"{_}Storage{_}{targetBucket.BucketName}{_}"; if (Directory.Exists(DirectoryPath) == false) { Directory.CreateDirectory(DirectoryPath); } using (var fileStream = new FileStream(DirectoryPath + newFile.FileKey + ".dat", FileMode.Create)) { await file.CopyToAsync(fileStream); fileStream.Close(); } // Get Internet path newFile.InternetPath = new AiurUrl(_serviceLocation.OSS, newFile.BelongingBucket.BucketName, newFile.RealFileName, new { }).ToString(); //Return json return(Json(new UploadFileViewModel { Code = ErrorType.Success, FileKey = newFile.FileKey, Message = "Successfully uploaded your file.", Path = newFile.InternetPath })); }
public async Task <IActionResult> UploadFile(UploadFileAddressModel model) { var site = await _siteRepo.GetSiteByName(model.SiteName); if (site == null) { return(this.Protocol(ErrorType.NotFound, $"Can't find a site with name: '{model.SiteName}'!")); } if (!site.OpenToUpload) { _tokenEnsurer.Ensure(model.Token, "Upload", model.SiteName, model.FolderNames); } var folders = _folderSplitter.SplitToFolders(model.FolderNames); var rootFolder = await _folderRepo.GetFolderFromId(site.RootFolderId); var folder = await _folderRepo.GetFolderFromPath(folders, rootFolder, model.RecursiveCreate); if (folder == null) { return(this.Protocol(ErrorType.NotFound, "Can't find your folder!")); } // Executing here will let the browser upload the file. try { var _ = HttpContext.Request.Form.Files.FirstOrDefault()?.ContentType; } catch (InvalidOperationException e) { return(this.Protocol(ErrorType.InvalidInput, e.Message)); } if (HttpContext.Request.Form.Files.Count < 1) { return(this.Protocol(ErrorType.InvalidInput, "Please provide a file!")); } var file = HttpContext.Request.Form.Files.First(); if (!new ValidFolderName().IsValid(file.FileName)) { return(this.Protocol(ErrorType.InvalidInput, $"Invalid file name: '{file.FileName}'!")); } var fileName = _folderSplitter.GetValidFileName(folder.Files.Select(t => t.FileName), file.FileName); var newFileHardwareId = await _fileRepo.SaveFileToDb(fileName, folder.Id, file.Length); await _storageProvider.Save(newFileHardwareId, file); var filePath = _probeLocator.GetProbeFullPath(model.SiteName, string.Join('/', folders), fileName); return(Ok(new UploadFileViewModel { InternetPath = _probeLocator.GetProbeOpenAddress(filePath), DownloadPath = _probeLocator.GetProbeDownloadAddress(filePath), SiteName = model.SiteName, FilePath = filePath, FileSize = file.Length, Code = ErrorType.Success, Message = "Successfully uploaded your file." })); }
public async Task <IActionResult> UploadFile(UploadFileAddressModel model) { var folders = _folderLocator.SplitStrings(model.FolderNames); var folder = await _folderLocator.LocateSiteAndFolder(model.AccessToken, model.SiteName, folders); var file = Request.Form.Files.First(); var newFile = new Pylon.Models.Probe.File { FileName = Path.GetFileName(file.FileName).ToLower(), ContextId = folder.Id }; //Ensure there not exists file with the same file name. lock (_obj) { var exists = folder.Files.Any(t => t.FileName == newFile.FileName); if (exists) { return(this.Protocol(ErrorType.HasDoneAlready, "There already exists a file with that name.")); } //Save to database _dbContext.Files.Add(newFile); _dbContext.SaveChanges(); } //Try saving file. string directoryPath = _configuration["StoragePath"] + $"{_}Storage{_}"; if (Directory.Exists(directoryPath) == false) { Directory.CreateDirectory(directoryPath); } using (var fileStream = new FileStream(directoryPath + newFile.Id + ".dat", FileMode.Create)) { await file.CopyToAsync(fileStream); fileStream.Close(); } return(this.Protocol(ErrorType.Success, "Successfully uploaded your file.")); }
public async Task <IActionResult> UploadFile(UploadFileAddressModel model) { var conversation = await _dbContext.Conversations.SingleOrDefaultAsync(t => t.Id == model.ConversationId); if (conversation == null) { return(this.Protocol(ErrorType.NotFound, $"找不到对应的会话: {model.ConversationId}!")); } var user = await _userManager.GetUserAsync(User); if (!await _dbContext.VerifyJoined(user.Id, conversation)) { return(this.Protocol(ErrorType.Unauthorized, $"您没有这个会话的文件上传权限: {conversation.Id}!")); } var file = Request.Form.Files.First(); var uploadedFile = await _storageService.SaveToOSS(file, Convert.ToInt32(_configuration["ChatSecretBucketId"]), 200); var fileRecord = new FileRecord { FileKey = uploadedFile.FileKey, SourceName = Path.GetFileName(file.FileName.Replace(" ", "")), UploaderId = user.Id, ConversationId = conversation.Id }; _dbContext.FileRecords.Add(fileRecord); await _dbContext.SaveChangesAsync(); return(this.ChatJson(new UploadFileViewModel { Code = ErrorType.Success, Message = "成功的上传了文件!", FileKey = uploadedFile.FileKey, SavedFileName = fileRecord.SourceName, FileSize = file.Length })); }
public async Task <IActionResult> UploadFile(UploadFileAddressModel model) { var conversation = await _dbContext.Conversations.SingleOrDefaultAsync(t => t.Id == model.ConversationId); if (conversation == null) { return(this.Protocol(ErrorType.NotFound, $"Could not find the target conversation with id: {model.ConversationId}!")); } var user = await GetKahlaUser(); if (!await _dbContext.VerifyJoined(user.Id, conversation)) { return(this.Protocol(ErrorType.Unauthorized, $"You are not authorized to upload file to conversation: {conversation.Id}!")); } var file = Request.Form.Files.First(); var uploadedFile = await _storageService.SaveToOSS(file, Convert.ToInt32(_configuration["KahlaSecretBucketId"]), 200); var fileRecord = new FileRecord { FileKey = uploadedFile.FileKey, SourceName = Path.GetFileName(file.FileName.Replace(" ", "")), UploaderId = user.Id, ConversationId = conversation.Id }; _dbContext.FileRecords.Add(fileRecord); await _dbContext.SaveChangesAsync(); return(this.AiurJson(new UploadFileViewModel { Code = ErrorType.Success, Message = "Successfully uploaded your file!", FileKey = uploadedFile.FileKey, SavedFileName = fileRecord.SourceName, FileSize = file.Length })); }
public async Task <IActionResult> UploadFile(UploadFileAddressModel model) { var site = await _dbContext .Sites .SingleOrDefaultAsync(t => t.SiteName.ToLower() == model.SiteName.ToLower()); if (!site.OpenToUpload) { _tokenEnsurer.Ensure(model.PBToken, "Upload", model.SiteName, model.FolderNames); } var folders = _folderLocator.SplitStrings(model.FolderNames); var folder = await _folderLocator.LocateSiteAndFolder(model.SiteName, folders, model.RecursiveCreate); // Executing here will let the browser upload the file. if (HttpContext.Request.Form.Files.Count < 1) { return(this.Protocol(ErrorType.InvalidInput, "Please provide a file!")); } var file = HttpContext.Request.Form.Files.First(); if (!new ValidFolderName().IsValid(file.FileName)) { return(this.Protocol(ErrorType.InvalidInput, $"Invalid file name: '{file.FileName}'!")); } var newFile = new SDK.Models.Probe.File { FileName = Path.GetFileName(file.FileName), ContextId = folder.Id, FileSize = file.Length }; //Ensure there not exists file with the same file name. while (true) { var exists = folder.Files.Any(t => t.FileName == newFile.FileName); if (exists) { newFile.FileName = "_" + newFile.FileName; } else { //Save to database _dbContext.Files.Add(newFile); _dbContext.SaveChanges(); break; } } //Try saving file. var directoryPath = _configuration["StoragePath"] + $"{_}Storage{_}"; if (Directory.Exists(directoryPath) == false) { Directory.CreateDirectory(directoryPath); } using (var fileStream = new FileStream(directoryPath + newFile.Id + ".dat", FileMode.Create)) { await file.CopyToAsync(fileStream); fileStream.Close(); } var filePath = StorageService.GetProbeFullPath(model.SiteName, string.Join('/', folders), newFile.FileName); var path = StorageService.GetProbeDownloadAddress(_serviceLocation, filePath); return(Json(new UploadFileViewModel { InternetPath = path, SiteName = model.SiteName, FilePath = filePath, FileSize = file.Length, Code = ErrorType.Success, Message = "Successfully uploaded your file." })); }
public async Task <IActionResult> UploadFile(UploadFileAddressModel model) { var folders = _folderLocator.SplitStrings(model.FolderNames); var folder = await _folderLocator.LocateSiteAndFolder(model.AccessToken, model.SiteName, folders, model.RecursiveCreate); var file = Request.Form.Files.First(); if (!new ValidFolderName().IsValid(file.FileName)) { var arg = new AiurProtocol() { Code = ErrorType.InvalidInput, Message = $"Invalid file name: '{file.FileName}'!" }; } var newFile = new Pylon.Models.Probe.File { FileName = Path.GetFileName(file.FileName), ContextId = folder.Id }; //Ensure there not exists file with the same file name. while (true) { var exists = folder.Files.Any(t => t.FileName == newFile.FileName); if (exists) { newFile.FileName = "_" + newFile.FileName; } else { //Save to database _dbContext.Files.Add(newFile); _dbContext.SaveChanges(); break; } } //Try saving file. var directoryPath = _configuration["StoragePath"] + $"{_}Storage{_}"; if (Directory.Exists(directoryPath) == false) { Directory.CreateDirectory(directoryPath); } using (var fileStream = new FileStream(directoryPath + newFile.Id + ".dat", FileMode.Create)) { await file.CopyToAsync(fileStream); fileStream.Close(); } var filePath = $"{string.Join('/', model.FolderNames)}/{newFile.FileName}".TrimStart('/'); var path = $"{_serviceLocation.Probe}/Download/{nameof(DownloadController.Open)}/{model.SiteName.ToUrlEncoded()}/{filePath.EncodePath()}"; return(Json(new UploadFileViewModel { InternetPath = path, SiteName = model.SiteName, FilePath = filePath, Code = ErrorType.Success, Message = "Successfully uploaded your file." })); }
public async Task <IActionResult> UploadFile(UploadFileAddressModel model) { var site = await _dbContext .Sites .Include(t => t.Root) .SingleOrDefaultAsync(t => t.SiteName.ToLower() == model.SiteName.ToLower()); if (site == null) { return(this.Protocol(ErrorType.NotFound, $"Can't find a site with name: '{model.SiteName}'!")); } if (!site.OpenToUpload) { _tokenEnsurer.Ensure(model.Token, "Upload", model.SiteName, model.FolderNames); } var folders = _folderLocator.SplitToFolders(model.FolderNames); var folder = await _folderLocator.LocateAsync(folders, site.Root, model.RecursiveCreate); if (folder == null) { return(this.Protocol(ErrorType.NotFound, $"Can't locate your folder!")); } try { var _ = HttpContext.Request.Form.Files.FirstOrDefault()?.ContentType; } catch (InvalidOperationException e) { return(this.Protocol(ErrorType.InvalidInput, e.Message)); } // Executing here will let the browser upload the file. if (HttpContext.Request.Form.Files.Count < 1) { return(this.Protocol(ErrorType.InvalidInput, "Please provide a file!")); } var file = HttpContext.Request.Form.Files.First(); if (!new ValidFolderName().IsValid(file.FileName)) { return(this.Protocol(ErrorType.InvalidInput, $"Invalid file name: '{file.FileName}'!")); } var newFile = new File { FileName = _folderLocator.GetValidFileName(folder.Files.Select(t => t.FileName), file.FileName), //file.FileName, ContextId = folder.Id, FileSize = file.Length }; // Save to disk await _storageProvider.Save(newFile.HardwareId, file); // Save to database _dbContext.Files.Add(newFile); await _dbContext.SaveChangesAsync(); var filePath = _probeLocator.GetProbeFullPath(model.SiteName, string.Join('/', folders), newFile.FileName); return(Json(new UploadFileViewModel { InternetPath = _probeLocator.GetProbeOpenAddress(filePath), DownloadPath = _probeLocator.GetProbeDownloadAddress(filePath), SiteName = model.SiteName, FilePath = filePath, FileSize = file.Length, Code = ErrorType.Success, Message = "Successfully uploaded your file." })); }