コード例 #1
0
ファイル: GlobalModel.cs プロジェクト: satishsonker/myshop
        public static string GetDbFileName(Enums.FileType ext)
        {
            switch (ext)
            {
            case Enums.FileType.Image:
                return("Img_" + DateTime.Now.Ticks.ToString());

            case Enums.FileType.MS_Excel:
                return("Excel_" + DateTime.Now.Ticks.ToString());

            case Enums.FileType.MS_PPT:
                return("Ppt_" + DateTime.Now.Ticks.ToString());

            case Enums.FileType.MS_Word:
                return("Word_" + DateTime.Now.Ticks.ToString());

            case Enums.FileType.Pdf:
                return("Pdf_" + DateTime.Now.Ticks.ToString());

            case Enums.FileType.TextFile:
                return("Text_" + DateTime.Now.Ticks.ToString());

            default:
                return("Common_" + DateTime.Now.Ticks.ToString());
            }
        }
コード例 #2
0
        public IEnumerable <ProductFileDto> GetProductFiles(int productId, Enums.FileType fileType)
        {
            if (productId <= 0)
            {
                return(null);
            }

            using (var cxt = DbContext(DbOperation.Read))
            {
                var repo = new ProductRepo(cxt);
                return(repo.GetProductFiles(productId, (int)fileType));
            }
        }
コード例 #3
0
ファイル: Helpers.cs プロジェクト: kotorihq/kotori-cli
        /// <summary>
        /// Get extesions for a given file type.
        /// </summary>
        /// <returns>List of extensions (incl. dot char).</returns>
        /// <param name="fileType">File type.</param>
        public static IEnumerable <string> ToExtensions(this Enums.FileType fileType)
        {
            switch (fileType)
            {
            case Enums.FileType.Documents:
                return(new []
                {
                    ".md"
                });

            default:
                throw new System.NotImplementedException("This conversion is not supported.");
            }
        }
コード例 #4
0
ファイル: DiskStorage.cs プロジェクト: kotorihq/kotori-cli
        /// <summary>
        /// Gets all files.
        /// </summary>
        /// <returns>The collection of files..</returns>
        /// <param name="path">Path.</param>
        /// <param name="recursive">If set to <c>true</c> recursive.</param>
        public InputFilesResult GetAll(string path, Enums.FileType fileType, bool recursive)
        {
            var di = new DirectoryInfo(path);

            if (!di.Exists)
            {
                return(new InputFilesResult(Enums.ResultCode.Fail, $"Input directory {path} does not exist."));
            }

            var extensions = fileType.ToExtensions();
            var files      = WalkDirectoryTree(di, extensions, recursive);

            return(new InputFilesResult(Enums.ResultCode.Ok, files));
        }
コード例 #5
0
        public AzureBlobPersistenceSystem(Enums.FileType fileType, Enums.FileSubType fileSubType, string folder) : base(fileType, fileSubType, folder)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // Create a CloudBlobClient object for credentialed access to storage.
            CloudBlobClient client = storageAccount.CreateCloudBlobClient();

            // Get a reference to the blob container.
            switch (FileType)
            {
            case Enums.FileType.Modelo:
                blobContainer = client.GetContainerReference("modelos");
                break;
            }
        }
コード例 #6
0
        public JsonResult UploadFile(Enums.FileType fileType)
        {
            try
            {
                var file = Request.Files[0];
                if (file == null)
                {
                    return(new JsonContractResult
                    {
                        Data =
                            new { data = new ActionDetails {
                                      ResponseCode = ResponseCode.ValidationError, Message = "file is not found"
                                  } },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    });
                }
                var    name      = Guid.NewGuid().ToString();
                string extension = Path.GetExtension(file.FileName);
                string filename  = $"{name}{extension}";
                // reduce original image size
                Image.FromStream(file.InputStream).ReduceSize().Save($"{Server.MapPath("/Files/" + fileType.ToString() + "/")}{filename}");
                //create thumb image
                Image.FromStream(file.InputStream).CreateThumb().Save($"{Server.MapPath("/Files/" + fileType.ToString() + "/thumb/")}{filename}");

                string filePath = $@"{GlobleConfig.baseUrl}/Files/{fileType.ToString()}/{name}{extension}";
                return(new JsonContractResult
                {
                    Data = new ActionDetails {
                        ResponseCode = ResponseCode.Success, Content = filePath, Message = filename
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                });
            }
            catch (Exception ex)
            {
                return(new JsonContractResult
                {
                    Data = ResponseMessage.Error(ex, "file is not uploaded"),
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                });
            }
        }
コード例 #7
0
        public string Download(long id, Enums.VideoService videoService, Enums.FileType fileType)
        {
            Video video = VideoLibrary.GetVideo(id);

            if (video is null)
            {
                return("Not found");
            }

            string file = null;

            if (videoService == Enums.VideoService.YouTube)
            {
                file = YouTubeDownloader.Download(video.URL);
            }
            else if (videoService == Enums.VideoService.Vimeo)
            {
                file = VimeoDownloader.Download(video.URL);
            }

            if (string.IsNullOrEmpty(file))
            {
                return("Not found");
            }

            if (fileType == Enums.FileType.MPEG4)
            {
                file = MPEG4Converter.Convert(file);
            }
            else if (fileType == Enums.FileType.Ogg)
            {
                file = OggConverter.Convert(file);
            }

            file = AudioMixer.IncreaseAudioQuality(file);

            return(file);
        }
コード例 #8
0
        public AzureFilePersistenceSystem(Enums.FileType fileType, Enums.FileSubType fileSubType, string folder) : base(fileType, fileSubType, folder)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // Create a CloudFileClient object for credentialed access to File storage.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            // Get a reference to the file share we created previously.
            CloudFileShare share = null;

            switch (FileType)
            {
            case Enums.FileType.Photo:
                share = fileClient.GetShareReference("photos");
                break;
            }

            // Ensure that the share exists.
            if (share.Exists())
            {
                // Get a reference to the root directory for the share.
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                // Get a reference to the directory we created previously.
                fileDirectory = rootDir.GetDirectoryReference(((int)FileSubType).ToString());
                if (!fileDirectory.Exists())
                {
                    fileDirectory.Create();
                }

                fileDirectory = fileDirectory.GetDirectoryReference(Folder);
                if (!fileDirectory.Exists())
                {
                    fileDirectory.Create();
                }
            }
        }
コード例 #9
0
        /// <summary>
        /// Validate all posted file
        /// </summary>
        /// <param name="Files">Collection fo files</param>
        /// <param name="FileType">Desire file format to validate</param>
        /// <param name="FileSize">Desire file size(KB) to validate</param>
        /// <returns></returns>
        protected internal Enums.FileValidateStatus ValidateFiles(HttpFileCollectionBase Files, Enums.FileType FileType, int MaxFileSize, int MaxFiles, int MinFileSize = 1)
        {
            bool IsInvalidFiles  = false;
            bool IsSizeOverflow  = false;
            bool IsSizeUnderflow = false;
            int  FileCounts      = 0;

            if (Files == null || Files.Count < 1)
            {
                return(Enums.FileValidateStatus.NoFiles);
            }
            else
            {
                foreach (string file in Files)
                {
                    if (Files[file].FileName == string.Empty)
                    {
                        return(Enums.FileValidateStatus.NoFiles);
                    }
                    else if (Enums.FileType.Image == FileType && (Path.GetExtension(Files[file].FileName).ToLower() != ".jpg" && Path.GetExtension(Files[file].FileName).ToLower() != ".jpeg"))
                    {
                        IsInvalidFiles = true;
                    }
                    else if (Enums.FileType.Pdf == FileType && Path.GetExtension(Files[file].FileName).ToLower() != ".pdf")
                    {
                        IsInvalidFiles = true;
                    }
                    else if ((Files[file].ContentLength / 1024) > MaxFileSize)
                    {
                        IsSizeOverflow = true;
                    }
                    else if ((Files[file].ContentLength / 1024) < MinFileSize)
                    {
                        IsSizeUnderflow = true;
                    }
                    FileCounts += 1;
                }

                if (IsInvalidFiles)
                {
                    return(Enums.FileValidateStatus.InvalidFormat);
                }
                else if (IsSizeOverflow)
                {
                    return(Enums.FileValidateStatus.SizeExceeded);
                }
                else if (IsSizeUnderflow)
                {
                    return(Enums.FileValidateStatus.SizeTooLow);
                }
                else if (FileCounts > MaxFiles)
                {
                    return(Enums.FileValidateStatus.MaxFilesLimitExceeded);
                }
                else
                {
                    return(Enums.FileValidateStatus.ValidFile);
                }
            }
        }
コード例 #10
0
 public LocalPersistenceSystem(Enums.FileType fileType, Enums.FileSubType fileSubType, string folder) : base(fileType, fileSubType, folder)
 {
 }
コード例 #11
0
ファイル: FileProcessing.cs プロジェクト: PathKnower/DNetCMS
        /// <summary>
        /// Upload file to the server storage and database
        /// </summary>
        /// <param name="file">Uploaded file</param>
        /// <param name="fileType">Target use</param>
        /// <returns>Success of operation</returns>
        public async Task <int> UploadFile(IFormFile file, Enums.FileType fileType)
        {
            if (file == null)
            {
                return(-1);
            }

            _logger.LogTrace($"Upload file method stared with filetype = {fileType.ToString()} and filename = {file.FileName}");
            _logger.LogTrace("Compute hash from file");
            string hash = GetHashFromFile(file.OpenReadStream());
            string dir1, dir2;

            _logger.LogTrace($"New file hash = {hash}");
            _logger.LogTrace("Determine path for new file");
            switch (fileType)
            {
            case Enums.FileType.Document:
                dir1 = _environment.WebRootPath + "/Files/Documents/";
                break;

            case Enums.FileType.Picture:
                dir1 = _environment.WebRootPath + "/Files/Picture/";
                break;

            case Enums.FileType.ToStore:
            default:
                dir1 = _environment.WebRootPath + "/Files/Storage/";
                break;
            }

            dir1 += $"{hash.Substring(0, 2)}";
            dir2  = $"{dir1}/{hash.Substring(2, 2)}/";

            _logger.LogTrace($"End directory path = {dir2}");
            _logger.LogTrace("Create directories");
            if (!Directory.Exists(dir1))
            {
                Directory.CreateDirectory(dir1);
                Directory.CreateDirectory(dir2);
            }
            else if (!Directory.Exists(dir2))
            {
                Directory.CreateDirectory(dir2);
            }

            FileModel result = new FileModel
            {
                FileType = (int)fileType,
                Name     = file.FileName,
                Path     = dir2 + file.FileName
            };

            _logger.LogTrace("Create file entity");
            _logger.LogTrace("Try to save file on disk");



            using (var fileStream = new FileStream(result.Path, FileMode.Create))
            {
                try
                {
                    await file.CopyToAsync(fileStream);
                }
                catch (Exception e)
                {
                    _logger.LogError($"UploadFile method with file = {file.FileName}, hash = {hash} \n and final" +
                                     $"path = {_environment.WebRootPath + result.Path} was thrown exception = {e.Message} \n " +
                                     $"with stack trace = {e.StackTrace}");
                    throw;
                }
            }

            await db.Files.AddAsync(result);

            await db.SaveChangesAsync();

            return(result.Id);
        }
コード例 #12
0
ファイル: FileProcessing.cs プロジェクト: PathKnower/DNetCMS
        /// <summary>
        /// Automaticly recognize file type and redirect to UploadFile method
        /// </summary>
        /// <param name="file">Uploaded file</param>
        /// <returns>Call result</returns>
        public async Task <int> UploadFile(IFormFile file)
        {
            Enums.FileType fileType = GetFileType(file);

            return(await UploadFile(file, fileType));
        }
コード例 #13
0
 /// <summary>
 /// Uploads a video owned by the current session user and returns the video.
 /// </summary>
 /// <example>
 /// <code>
 /// private static void RunDemoAsync()
 /// {
 ///     Api api = new Api(new DesktopSession(Constants.ApplicationKey, Constants.ApplicationSecret, Constants.SessionSecret, Constants.SessionKey));
 ///     var filePath = @"C:\Butterfly.wmv";
 ///     var fileStream = System.IO.File.OpenRead(filePath);
 ///     var reader = new System.IO.BinaryReader(fileStream);
 ///     var fileData = reader.ReadBytes((int)fileStream.Length);
 ///     api.Video.UploadAsync("test", "video upload test", System.IO.Path.GetFileName(filePath), fileData, "video/avi", AsyncDemoCompleted, null);
 /// }
 ///
 /// private static void AsyncDemoCompleted(video result, Object state, FacebookException e)
 /// {
 ///     var actual = result;
 /// }
 /// </code>
 /// </example>
 /// <param name="title">The name of the video. The name cannot be longer than 65 characters. Longer titles will get truncated and will not return an error.</param>
 /// <param name="description">A description of the video. There is no limit to the length of the description.</param>
 /// <param name="data">The raw image data for the video.</param>
 /// <param name="fileType">One of the video type</param>
 /// <param name="callback">The AsyncCallback delegate</param>
 /// <param name="state">An object containing state information for this asynchronous request</param>
 /// <returns>This method returns a video object containing information about the uploaded object.</returns>
 public void UploadAsync(string title, string description, byte[] data, Enums.FileType fileType, UploadCallback callback, Object state)
 {
     Upload(title, description, null, data, _mimeTypes[fileType], true, callback, state);
 }