Beispiel #1
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
                });
            }
        }
Beispiel #2
0
        /// <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);
        }