コード例 #1
0
        public async Task <UploadResult> ProcessFile(
            IFormFile formFile,
            ImageProcessingOptions options,
            bool?resizeImages,
            int?maxWidth,
            int?maxHeight,
            string requestedVirtualPath = "",
            string newFileName          = "",
            bool allowRootPath          = true,
            bool createThumbnail        = false,
            bool?keepOriginal           = null
            )
        {
            await EnsureProjectSettings().ConfigureAwait(false);

            string currentFsPath      = _rootPath.RootFileSystemPath;
            string currentVirtualPath = _rootPath.RootVirtualPath;

            string[] virtualSegments = options.ImageDefaultVirtualSubPath.Split('/');
            bool     doResize        = resizeImages ?? options.AutoResize;

            if ((!string.IsNullOrEmpty(requestedVirtualPath)) && (requestedVirtualPath.StartsWith(_rootPath.RootVirtualPath)))
            {
                var virtualSubPath = requestedVirtualPath.Substring(_rootPath.RootVirtualPath.Length);
                var segments       = virtualSubPath.Split('/');
                if (segments.Length > 0)
                {
                    var requestedFsPath = Path.Combine(_rootPath.RootFileSystemPath, Path.Combine(segments));
                    if (!Directory.Exists(requestedFsPath))
                    {
                        //_log.LogError("directory not found for currentPath " + requestedFsPath);
                        // user has file system permission and could manually create the needed folder so auto ensure
                        // since it is a sub path of the root
                        EnsureSubFolders(_rootPath.RootFileSystemPath, segments);
                    }

                    currentVirtualPath = requestedVirtualPath;
                    virtualSegments    = segments;
                    currentFsPath      = Path.Combine(currentFsPath, Path.Combine(virtualSegments));
                }
            }
            else
            {
                // ensure the folders if no currentDir provided,
                // if it is provided it must be an existing path
                // options.ImageDefaultVirtualSubPath might not exist on first upload so need to ensure it
                if (!allowRootPath)
                {
                    currentVirtualPath = currentVirtualPath + options.ImageDefaultVirtualSubPath;
                    currentFsPath      = Path.Combine(currentFsPath, Path.Combine(virtualSegments));
                    EnsureSubFolders(_rootPath.RootFileSystemPath, virtualSegments);
                }
            }
            string newName;

            if (!string.IsNullOrEmpty(newFileName))
            {
                newName = _nameRules.GetCleanFileName(newFileName);
            }
            else
            {
                newName = _nameRules.GetCleanFileName(Path.GetFileName(formFile.FileName));
            }

            var newUrl = currentVirtualPath + "/" + newName;
            var fsPath = Path.Combine(currentFsPath, newName);

            var ext         = Path.GetExtension(newName);
            var webSizeName = Path.GetFileNameWithoutExtension(newName) + "-ws" + ext;

            string webUrl = currentVirtualPath + "/" + webSizeName;

            var    thumbSizeName = Path.GetFileNameWithoutExtension(newName) + "-thumb" + ext;
            string thumbUrl      = currentVirtualPath + "/" + thumbSizeName;

            var didResize      = false;
            var didCreateThumb = false;

            try
            {
                using (var stream = new FileStream(fsPath, FileMode.Create))
                {
                    await formFile.CopyToAsync(stream);
                }
                var mimeType = GetMimeType(ext);

                if ((doResize) && IsWebImageFile(ext))
                {
                    int resizeWidth  = GetMaxWidth(maxWidth, options);
                    int resizeHeight = GetMaxWidth(maxHeight, options);

                    didResize = _imageResizer.ResizeImage(
                        fsPath,
                        currentFsPath,
                        webSizeName,
                        mimeType,
                        resizeWidth,
                        resizeHeight,
                        options.AllowEnlargement,
                        options.ResizeQuality
                        );
                }

                if (createThumbnail)
                {
                    didCreateThumb = _imageResizer.ResizeImage(
                        fsPath,
                        currentFsPath,
                        thumbSizeName,
                        mimeType,
                        options.ThumbnailImageMaxWidth,
                        options.ThumbnailImageMaxHeight,
                        false,
                        options.ResizeQuality
                        );
                }
                if (didResize)
                {
                    if (keepOriginal.HasValue)
                    {
                        if (keepOriginal.Value == false)
                        {
                            File.Delete(fsPath);
                            newUrl = string.Empty;
                        }
                    }
                    else if (!options.KeepOriginalImages) // use default if not explcitely passed
                    {
                        File.Delete(fsPath);
                        newUrl = string.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                _log.LogError($"{ex.Message}:{ex.StackTrace}");

                return(new UploadResult
                {
                    ErrorMessage = _sr["There was an error logged during file processing"]
                });
            }

            return(new UploadResult
            {
                OriginalUrl = newUrl,
                ResizedUrl = didResize ? webUrl : string.Empty,
                ThumbUrl = didCreateThumb ? thumbUrl : string.Empty,
                Name = newName,
                Length = formFile.Length,
                Type = formFile.ContentType
            });
        }
コード例 #2
0
        public async Task <OperationResult> RenameFile(string requestedVirtualPath, string newNameSegment)
        {
            OperationResult result;

            if (string.IsNullOrEmpty(requestedVirtualPath))
            {
                result         = new OperationResult(false);
                result.Message = sr["Path not provided"];
                return(result);
            }

            if (string.IsNullOrEmpty(newNameSegment))
            {
                result         = new OperationResult(false);
                result.Message = sr["New name not provided"];
                return(result);
            }

            await EnsureProjectSettings().ConfigureAwait(false);

            if (!requestedVirtualPath.StartsWith(rootPath.RootVirtualPath))
            {
                result         = new OperationResult(false);
                result.Message = sr["Invalid path"];
                return(result);
            }

            var virtualSubPath = requestedVirtualPath.Substring(rootPath.RootVirtualPath.Length);
            var segments       = virtualSubPath.Split('/');

            if (segments.Length == 0)
            {
                // don't allow delete the root folder
                result         = new OperationResult(false);
                result.Message = sr["Invalid path"];
                return(result);
            }

            var currentFsPath = Path.Combine(rootPath.RootFileSystemPath, Path.Combine(segments));
            var ext           = Path.GetExtension(currentFsPath);

            if (!File.Exists(currentFsPath))
            {
                result         = new OperationResult(false);
                result.Message = sr["Invalid path"];
                return(result);
            }

            // pop the last segment
            segments = segments.Take(segments.Count() - 1).ToArray();

            if (Path.HasExtension(newNameSegment) && Path.GetExtension(newNameSegment) == ext)
            {
                // all good
            }
            else
            {
                newNameSegment = Path.GetFileNameWithoutExtension(newNameSegment) + ext;
            }
            var cleanFileName = nameRules.GetCleanFileName(newNameSegment);

            string newFsPath;

            if (segments.Length > 0)
            {
                newFsPath = Path.Combine(Path.Combine(rootPath.RootFileSystemPath, Path.Combine(segments)), cleanFileName);
            }
            else
            {
                newFsPath = Path.Combine(rootPath.RootFileSystemPath, cleanFileName);
            }


            if (File.Exists(newFsPath))
            {
                result         = new OperationResult(false);
                result.Message = sr["Directory already exists"];
                return(result);
            }

            try
            {
                File.Move(currentFsPath, newFsPath);
                result = new OperationResult(true);
                return(result);
            }
            catch (IOException ex)
            {
                log.LogError(MediaLoggingEvents.FOLDER_RENAME, ex, ex.Message + " " + ex.StackTrace);
                result         = new OperationResult(false);
                result.Message = sr["A error was logged while processing the request"];
                return(result);
            }
        }