private async Task <XRpcStruct> MetaWeblogNewMediaObjectAsync(string userName, string password, XRpcStruct file) { var user = await ValidateUserAsync(userName, password); var name = file.Optional <string>("name"); var bits = file.Optional <byte[]>("bits"); var directoryName = Path.GetDirectoryName(name); var filePath = _mediaFileStore.Combine(directoryName, Path.GetFileName(name)); Stream stream = null; try { stream = new MemoryStream(bits); filePath = await _mediaFileStore.CreateFileFromStreamAsync(filePath, stream); } finally { stream?.Dispose(); } var publicUrl = _mediaFileStore.MapPathToPublicUrl(filePath); return(new XRpcStruct() // Some clients require all optional attributes to be declared Wordpress responds in this way as well. .Set("file", publicUrl) .Set("url", publicUrl) .Set("type", file.Optional <string>("type"))); }
public async Task <string> CreateFile() { using var stream = new MemoryStream(Encoding.UTF8.GetBytes("Hello world!")); await _mediaFileStore.CreateFileFromStreamAsync("Demo.txt", stream); return("OK"); }
// This action will demonstrate how to create a file in the Media folder and read it from there. public async Task <string> CreateFileInMediaFolder() { // You need to initialize a stream if you have a specific text you want to write into the file. If you // already have a stream for that just use it (you'll see it later)! using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("Hi there!"))) { // The third parameter here is optional - if true, it will override the file if already exists. await _mediaFileStore.CreateFileFromStreamAsync(TestFileRelativePath, stream, true); } // Use this method to check if the file exists (it will be null if the file doesn't exist). It's similar to // the built-in FileInfo class but not that robust. var fileInfo = await _mediaFileStore.GetFileInfoAsync(TestFileRelativePath); // The IMediaFileStore has its own specific methods such as mapping the file path to a public URL. Since // the files in the Media folder are accessible from the outside this can be handy. var publicUrl = _mediaFileStore.MapPathToPublicUrl(TestFileRelativePath); return($"Successfully created file! File size: {fileInfo.Length} bytes. Public URL: {publicUrl}"); }
public async Task <ActionResult <object> > Upload( string path, string contentType, ICollection <IFormFile> files) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia)) { return(Forbid()); } if (string.IsNullOrEmpty(path)) { path = ""; } var result = new List <object>(); // Loop through each file in the request foreach (var file in files) { // TODO: support clipboard if (!_allowedFileExtensions.Contains(Path.GetExtension(file.FileName), StringComparer.OrdinalIgnoreCase)) { result.Add(new { name = file.FileName, size = file.Length, folder = path, error = S["This file extension is not allowed: {0}", Path.GetExtension(file.FileName)].ToString() }); _logger.LogInformation("File extension not allowed: '{0}'", file.FileName); continue; } var fileName = _mediaNameNormalizerService.NormalizeFileName(file.FileName); Stream stream = null; try { var mediaFilePath = _mediaFileStore.Combine(path, fileName); stream = file.OpenReadStream(); mediaFilePath = await _mediaFileStore.CreateFileFromStreamAsync(mediaFilePath, stream); var mediaFile = await _mediaFileStore.GetFileInfoAsync(mediaFilePath); result.Add(CreateFileResult(mediaFile)); } catch (Exception ex) { _logger.LogError(ex, "An error occurred while uploading a media"); result.Add(new { name = fileName, size = file.Length, folder = path, error = ex.Message }); } finally { stream?.Dispose(); } } return(new { files = result.ToArray() }); }
// Newly added files private async Task <object> MoveNewFilesToContentItemDirAndUpdatePaths1(IFormFile fileToUpload, ContentItem contentItem) { // Generate Random name. string extension = Utils.GetFileExtension(fileToUpload.FileName); // string name = $"{Utils.GenerateUniqueString()}.{extension}"; string uniqueName = Utils.GenerateUniqueString(); string name = $"{uniqueName}.{extension}"; // string link = fileRoute + name; var targetDir = GetContentItemFolder(contentItem); // var finalFileName = (await GetFileHashAsync(x.Path)) + GetFileExtension(x.Path); var finalFileName = name;//(await GetFileHashAsync(uniqueName)) + extension;// GetFileExtension(x.Path); var finalFilePath = _fileStore.Combine(targetDir, finalFileName); // string link = finalFilePath; await _fileStore.TryCreateDirectoryAsync(targetDir); // When there is a validation error before creating the content item we can end up with an empty folder // because the content item is different on each form submit . We need to remove that empty folder. // var previousDirPath = (await _fileStore.GetFileInfoAsync(x.Path)).DirectoryPath; //var previousDirPath = (await _fileStore.GetFileInfoAsync(name)).DirectoryPath; // fileName is a hash of the file. We preserve disk space by reusing the file. //if (await _fileStore.GetFileInfoAsync(finalFilePath) == null) //{ // Copy contents to memory stream. Stream stream; stream = new MemoryStream(); fileToUpload.CopyTo(stream); stream.Position = 0; // await _fileStore.MoveFileAsync(x.Path, finalFilePath); await _fileStore.CreateFileFromStreamAsync(finalFilePath, stream); // ..MoveFileAsync(x.Path, finalFilePath); //} // x.Path = finalFilePath; //await DeleteDirIfEmpty(previousDirPath); string link = _fileStore.MapPathToPublicUrl(finalFilePath); // Make sure it is compatible with ASP.NET Core. return(new { link = link }); // return new { link = Path.Combine( "/media/" ,link) }; // return new { link = link.Replace("wwwroot/", "/") }; /* * items.Where(x => !x.IsRemoved).ToList() * .ForEach(async x => * { * var targetDir = GetContentItemFolder(contentItem); * var finalFileName = (await GetFileHashAsync(x.Path)) + GetFileExtension(x.Path); * var finalFilePath = _fileStore.Combine(targetDir, finalFileName); * * await _fileStore.TryCreateDirectoryAsync(targetDir); * * // When there is a validation error before creating the content item we can end up with an empty folder * // because the content item is different on each form submit . We need to remove that empty folder. * var previousDirPath = (await _fileStore.GetFileInfoAsync(x.Path)).DirectoryPath; * * // fileName is a hash of the file. We preserve disk space by reusing the file. * if (await _fileStore.GetFileInfoAsync(finalFilePath) == null) * { * await _fileStore.MoveFileAsync(x.Path, finalFilePath); * } * * x.Path = finalFilePath; * * await DeleteDirIfEmpty(previousDirPath); * * }); */ }
public async Task <IActionResult> UploadMediaFromFroalaEditor() { // if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOwnMedia)) // { // return Forbid(); // } var path = _attachedMediaToContentItemService.MediaFieldsTempSubFolder; var fileToUpload = GetFileToUpload(null); var result = new object(); // Loop through each file in the request // foreach (var file in files) //{ if (fileToUpload != null) { // TODO: support clipboard if (!_allowedFileExtensions.Contains(Path.GetExtension(fileToUpload.FileName), StringComparer.OrdinalIgnoreCase)) { result = new { name = fileToUpload.FileName, size = fileToUpload.Length, folder = path, error = S["This file extension is not allowed: {0}", Path.GetExtension(fileToUpload.FileName)] .ToString() }; _logger.LogInformation("File extension not allowed: '{0}'", fileToUpload.FileName); // continue; } else { Stream stream = null; try { var mediaFilePath = _mediaFileStore.Combine(path, fileToUpload.FileName); stream = fileToUpload.OpenReadStream(); mediaFilePath = await _mediaFileStore.CreateFileFromStreamAsync(mediaFilePath, stream); var mediaFile = await _mediaFileStore.GetFileInfoAsync(mediaFilePath); result = CreateFileResult(mediaFile); } catch (Exception ex) { _logger.LogError(ex, "An error occurred while uploading a media"); result = new { name = fileToUpload.FileName, size = fileToUpload.Length, folder = path, error = ex.Message }; } finally { stream?.Dispose(); } } //} } return(Json(result)); }