示例#1
0
        public Either <IError, UploadFileDto> UploadFile(string token, UploadFileDto uploadFile)
        {
            if (uploadFile.Path.Equals("/"))
            {
                return(new Left <IError, UploadFileDto>(new FormatError("You must be in bucket to upload file.", Either.Enums.ErrorCode.PutFileError)));
            }
            Message <BucketMessage> message;

            using (Stream stream = new MemoryStream())
            {
                uploadFile.File.CopyTo(stream);
                message = new Message <BucketMessage>("bucket/putFile")
                {
                    Data = new BucketMessage()
                    {
                        Token = token,
                        Path  = uploadFile.Path + uploadFile.Value
                    },
                    Bytes = new NetMQFrame(stream.ToByteArray())
                };
            }
            NetMQMessage response = RequestSocketFactory.SendRequest(message.ToNetMQMessage());

            string responseTopic = response.First.ConvertToString();


            if (responseTopic.Equals("Response"))
            {
                return(new Right <IError, UploadFileDto>(uploadFile));
            }

            return(new Left <IError, UploadFileDto>(GetError(response)));
        }
示例#2
0
        /// <summary>
        /// Saves the file.
        /// </summary>
        /// <param name="model">The HTTP posted file.</param>
        /// <returns></returns>
        public UploadFileResponseDto SaveFile(UploadFileDto model)
        {
            string relativePath = null;

            if (model != null && !string.IsNullOrEmpty(model.FileName))
            {
                // TODO: Validate file.
                var fileName         = model.FileName;
                var indexOfExtension = fileName.LastIndexOf('.');
                var fileExtension    = fileName.Substring(indexOfExtension);

                var newFileName = string.Format("{0}{1}", Guid.NewGuid(), fileExtension);

                string filePath = Path.Combine(
                    HostingEnvironment.MapPath(Settings.UploadImagesFolder),
                    newFileName);

                var stream = new MemoryStream(Convert.FromBase64String(model.FileData));

                var image = Image.FromStream(stream);

                image.Save(filePath);

                relativePath = VirtualPathUtility.ToAbsolute(string.Format("{0}/{1}",
                                                                           Settings.UploadImagesFolder, newFileName));
            }

            return(new UploadFileResponseDto()
            {
                FilePath = string.Format("{0}{1}", Settings.ApiBaseUrl, relativePath),
            });
        }
示例#3
0
 public async Task UploadFileAsync(UploadFileDto model)
 {
     using (var fileStream = new FileStream(model.FilePath + "/" + model.UploadedFile.FileName, FileMode.Create))
     {
         await model.UploadedFile.CopyToAsync(fileStream);
     }
 }
示例#4
0
        public async Task <ServiceResponse <object> > UploadFile(UploadFileDto model)
        {
            try
            {
                //string contentRootPath = _HostEnvironment.ContentRootPath;


                var pathToSave = "http://localhost:8000/images";


                var fileName = Guid.NewGuid().ToString() + Path.GetExtension(model.File.FileName);
                //var fullPath = Path.Combine(pathToSave);
                //var dbPath = Path.Combine(pathToSave, fileName); //you can add this path to a list and then return all dbPaths to the client if require
                //if (!Directory.Exists(fullPath))
                //{
                //    //If Directory (Folder) does not exists. Create it.
                //    //Directory.CreateDirectory(fullPath);
                //}
                //var filePath = Path.Combine(pathToSave, fileName);
                string contentRootPath = _webHostEnvironment.ContentRootPath;
                var    filePath        = Path.Combine(contentRootPath, "SchoolDocuments", fileName);


                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await model.File.CopyToAsync(stream);
                }
                return(_serviceResponse);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#5
0
        public void WhenIUploadTheFile(UploadFileDto uploadFile)
        {
            var filePath = ContextHelper.GetFromContext <string>("FilePath");
            var file     = File.ReadAllBytes(filePath);
            var response = new DropboxApiContent().UploadFile(uploadFile, file);

            response.EnsureSuccessful();
            ContextHelper.AddToContext("LastApiResponse", response);
        }
示例#6
0
        public ApiResponse UploadFile(UploadFileDto uploadDto, byte[] file)
        {
            var url         = "files/upload";
            var requestBody = JsonConvert.SerializeObject(uploadDto);

            return(request.Uri(url).Method(HttpMethod.Post)
                   .WithHeader("Dropbox-API-Arg", requestBody)
                   .WithFile(file)
                   .Execute());
        }
示例#7
0
        public async Task <ActionResult <BaseResponse <TempUploadFileDto> > > UploadFile(
            [FromForm][Required] UploadFileDto dto
            )
        {
            var response = new BaseResponse <TempUploadFileDto>
            {
                Data   = await _fileService.UploadTempFile(dto.File),
                Status = true
            };

            return(Ok(response));
        }
示例#8
0
        public void UploadFile(UploadFileDto input)
        {
            var userClaim = _userService.UserClaim();

            _fileRepository.InsertAsync(new FileEntity
            {
                Id           = input.Id,
                FileName     = input.FileName,
                FileSuffix   = input.FileSuffix,
                FileUrl      = input.FileUrl,
                CreateUserId = userClaim.UserId
            });
        }
示例#9
0
        public async Task <MessageModel <string> > InsertPicture([FromForm] UploadFileDto dto)
        {
            if (dto.Files == null || !dto.Files.Any())
            {
                return(Failed("请选择上传的文件。"));
            }
            //格式限制
            var allowType = new string[] { "image/jpg", "image/png", "image/jpeg" };

            var allowedFile = dto.Files.Where(c => allowType.Contains(c.ContentType));

            if (!allowedFile.Any())
            {
                return(Failed("图片格式错误"));
            }
            if (allowedFile.Sum(c => c.Length) > 1024 * 1024 * 4)
            {
                return(Failed("图片过大"));
            }

            string foldername = "images";
            string folderpath = Path.Combine(_env.WebRootPath, foldername);

            if (!Directory.Exists(folderpath))
            {
                Directory.CreateDirectory(folderpath);
            }
            foreach (var file in allowedFile)
            {
                string strpath = Path.Combine(foldername, DateTime.Now.ToString("MMddHHmmss") + Path.GetFileName(file.FileName));
                var    path    = Path.Combine(_env.WebRootPath, strpath);

                using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    await file.CopyToAsync(stream);
                }
            }

            var excludeFiles = dto.Files.Except(allowedFile);

            if (excludeFiles.Any())
            {
                var infoMsg = $"{string.Join('、', excludeFiles.Select(c => c.FileName))} 图片格式错误";
                return(Success <string>(null, infoMsg));
            }

            return(Success <string>(null, "上传成功"));
        }
        public async Task <Tuple <bool, FileDto, string> > UpdateFile(UploadFileDto file)
        {
            var url = await UploadFileToBlob(file.Name, file.FileMimeType, file.FileData);

            if (!string.IsNullOrEmpty(url))
            {
                var fileModel = file.MergeToDestination <File>();
                fileModel.URL = url;

                await _fileRepository.Create(fileModel);

                return(new Tuple <bool, FileDto, string>(false, fileModel.MergeToDestination <FileDto>(), string.Empty));
            }

            return(new Tuple <bool, FileDto, string>(true, null, "Error getting URL"));
        }
示例#11
0
        public void Execute(UploadFileDto request)
        {
            _validator.ValidateAndThrow(request);

            var guid      = Guid.NewGuid();
            var extension = Path.GetExtension(request.Image.FileName);

            var newFileName = guid + extension;

            var path = Path.Combine("wwwroot", "images", newFileName);

            using (var fileStream = new FileStream(path, FileMode.Create))
            {
                request.Image.CopyTo(fileStream);
            }
        }
        public async Task <IActionResult> Post([FromBody] UploadFileDto newFile)
        {
            var model = new File
            {
                Content     = newFile.Content,
                MimeType    = newFile.MimeType,
                DisplayName = newFile.DisplayName,
                UploadDate  = DateTimeOffset.UtcNow,
                ModifyDate  = DateTimeOffset.UtcNow
            };

            _dbContext.Files.Add(model);
            await _dbContext.SaveChangesAsync();

            return(CreatedAtAction(nameof(Get), new { fileGuid = model.Id }, model));
        }
示例#13
0
        public static void UploadFile(string fileName)
        {
            var filePath = GetFilePath(fileName);

            File.Exists(filePath)
            .Should()
            .BeTrue($"expected {fileName} to exists with test fata files inside the {filePath}");
            var uploadFile = new UploadFileDto();

            uploadFile.Mode       = "add";
            uploadFile.AutoRename = true;
            uploadFile.Mute       = false;
            uploadFile.Path       = fileName;
            var file     = File.ReadAllBytes(filePath);
            var response = new DropboxApiContent().UploadFile(uploadFile, file);

            response.EnsureSuccessful();
        }
示例#14
0
        public async Task <IActionResult> UploadMedia([FromForm] UploadFileDto uploadFile)
        {
            if (uploadFile.file is null || uploadFile.file.Length < 5)
            {
                return(Problem());
            }

            string username = HttpContext?.User?.Identity?.Name;

            ComputerVisionClient client = new ComputerVisionClient(new ApiKeyServiceClientCredentials(KEY))
            {
                Endpoint = ENDPOINT
            };

            using Stream stream = uploadFile.file.OpenReadStream();
            byte[] buffer = new byte[stream.Length];
            int    pos    = await stream.ReadAsync(buffer, 0, (int)stream.Length);

            using MemoryStream ms = new MemoryStream(buffer);
            var result = await client.TagImageInStreamAsync(ms);

            string[] invalid = { "penis", "v****a", "sex", "murder", "t**s", "boobs", "kill", "drug" };
            if (result.Tags.Any(t => invalid.Contains(t.Name)))
            {
                throw new Exception("Sensitive picture uploaded");
            }

            if (username is default(string))
            {
                throw new ArgumentNullException("user");
            }

            if (!_accountService.TryGetIdentifierByUsername(username, out var userId))
            {
                throw new ArgumentException(nameof(username));
            }

            _context.Medias.Add(new Media(Guid.NewGuid().ToString(), buffer, uploadFile.text, userId,
                                          uploadFile.file.ContentType, DateTime.Now));
            await _context.SaveChangesAsync();

            return(Ok());
        }
        public async Task <IActionResult> Upload([FromForm] UploadFileDto model)
        {
            Guid?id = null;

            try
            {
                var fileEntry = new Models.File
                {
                    Description  = model.Description,
                    Size         = model.FormFile.Length,
                    UploadedTime = DateTime.Now,
                    FileName     = model.FormFile.FileName,
                };

                id = _repository.Add(fileEntry);

                using (var stream = new MemoryStream())
                {
                    await model.FormFile.CopyToAsync(stream);

                    _storageManager.Create(fileEntry, stream);
                }

                _repository.Update(fileEntry);

                return(Ok(fileEntry.Id));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());

                if (id.HasValue)
                {
                    _repository.Delete(id.Value);
                }

                return(BadRequest());
            }
        }
        public ActionResult <List <FileDto> > InsertFile([FromForm] UploadFileDto uploadFileDto)
        {
            List <FileDto> response = null;

            try
            {
                if (Request.Form.Files.Count > Constant.Zero && !string.IsNullOrEmpty(uploadFileDto.FolderIdDto))
                {
                    response = _iDriveService.InsertFile(uploadFileDto.FolderIdDto, Request.Form.Files);
                }
                else
                {
                    return(NotFound(Constant.CreateFileError));
                }
            }
            catch (Exception e)
            {
                Logger.Error(e.StackTrace);
            }

            return(Ok(response));
        }
        public IHttpActionResult UploadFile(UploadFileDto file)
        {
            if (file != null && !string.IsNullOrEmpty(file.FileData))
            {
                var fileResponse = fileUploaderHelper.SaveFile(file);

                if (fileResponse != null && !string.IsNullOrEmpty(fileResponse.FilePath))
                {
                    return(Ok(fileResponse));
                }
            }

            return(Content(
                       HttpStatusCode.BadRequest,
                       new ErrorResponseDto()
            {
                Error = ErrorCode.InvalidRequest,
                Message = ErrorCode.InvalidRequest.Description(),
                Details = ErrorCode.IncorrectFile.Description()
            }
                       ));
        }
        public async Task <IActionResult> Modify(Guid fileGuid, [FromBody] UploadFileDto changeData)
        {
            var file = await _dbContext.Files.FindAsync(fileGuid);

            if (file == null)
            {
                return(NotFound());
            }

            file.DisplayName = changeData.DisplayName;
            if (changeData.MimeType != null)
            {
                file.MimeType = changeData.MimeType;
                if (changeData.Content != null)
                {
                    file.Content = changeData.Content;
                }
            }

            _dbContext.Update(file);
            await _dbContext.SaveChangesAsync();

            return(NoContent());
        }
示例#19
0
 public IActionResult UploadFile([FromForm] UploadFileDto uploadFile) =>
 _bucketService.UploadFile(Request.Headers["token"], uploadFile)
 .Map((x) => AllOk(x))
 .Reduce(NotFoundErrorHandler, x => x is NotFoundError)
 .Reduce(InternalServisErrorHandler);
        public async Task <List <UploadFileDto> > Upload()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new UserFriendlyException("上传格式不是multipart/form-data");
            }

            //创建保存上传文件的物理路径
            var root = System.Web.Hosting.HostingEnvironment.MapPath(GetUploadSavePath());

            //如果路径不存在,创建路径
            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }

            var provider = new MultipartFormDataStreamProvider(root);

            //读取 MIME 多部分消息中的所有正文部分,并生成一组 HttpContent 实例作为结果
            await Request.Content.ReadAsMultipartAsync(provider);

            List <UploadFileDto> uploadFileResultList = new List <UploadFileDto>();

            foreach (var file in provider.FileData)
            {
                //获取上传文件名 这里获取含有双引号'" '
                string fileName = file.Headers.ContentDisposition.FileName.Trim('"');
                //获取上传文件后缀名
                string fileExt = fileName.Substring(fileName.LastIndexOf('.')).ToLower();

                FileInfo fileInfo = new FileInfo(file.LocalFileName);

                if (fileInfo.Length > 0 && fileInfo.Length <= GetUploadMaxByte())
                {
                    if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(GetUploadType().Split(','), fileExt.Substring(1).ToLower()) == -1)
                    {
                        fileInfo.Delete();
                        throw new UserFriendlyException("上传的文件格式不支持");
                    }
                    else
                    {
                        UploadFileDto uploadFile = new UploadFileDto
                        {
                            Id         = Guid.NewGuid(),
                            FileName   = fileName,
                            FileSuffix = fileExt
                        };
                        uploadFile.FileUrl = GetFullHost() + GetUploadSavePath() + uploadFile.Id.ToString() + fileExt;

                        fileInfo.MoveTo(Path.Combine(root, uploadFile.Id.ToString() + fileExt));
                        uploadFileResultList.Add(uploadFile);
                        _fileService.UploadFile(uploadFile);
                    }
                }
                else
                {
                    fileInfo.Delete();
                    throw new UserFriendlyException("上传文件的大小不符合");
                }
            }
            return(uploadFileResultList);
        }
示例#21
0
 public UploadFile_request(UploadFileDto uploadDto, byte[] file)
 {
     this.uploadDto = uploadDto;
     this.file      = file;
 }
示例#22
0
        public bool Upload([FromForm] UploadFileDto data)
        {
            var id = documentService.UploadFile(data.Content.OpenReadStream(), data.Content.FileName);

            return(service.SetMainImage(data.ProductId, id));
        }
        public async Task <JsonResult> UploadFile(UploadFileDto input)
        {
            string ext = Path.GetExtension(input.File.FileName);

            if (!AppConsts.Extentions.Contains(ext))
            {
                return(new JsonResult(new ResponseModel(message: "Error while uploading file", code: HttpStatusCode.BadRequest, success: false, errors: new List <string> {
                    "Wrong file type selected"
                })));
            }
            var fileEntity = CustomMapper <UploadFileDto, FileEntity> .Map(input);

            long userId = long.Parse(User.Identity.Name);
            var  user   = await _userManager.GetAsync(x => x.Id == userId);

            fileEntity.Type    = FileEntityType.File;
            fileEntity.OwnerId = userId;
            bool exists = await _fileManager.IsExist(fileEntity.ParentId, fileEntity.OwnerId, input.Name);

            if (exists)
            {
                return(new JsonResult(new ResponseModel(message: "Error while uploading file", code: HttpStatusCode.BadRequest, success: false,
                                                        errors: new List <string> {
                    $"File with name {input.Name} already exists"
                })));
            }

            double freeSpasce = await Dir.GetFreeSpase(user, _env, _fileManager);

            double fileSize = input.File.Length / Math.Pow(1024, 2);

            if (freeSpasce < fileSize)
            {
                return(new JsonResult(new ResponseModel(message: "Error while uploading file", code: HttpStatusCode.BadRequest, success: false, errors: new List <string> {
                    "File is too big.You haven't enough free space"
                })));
            }

            string connId = ProgressHub.Connections.Where(x => x.Key == fileEntity.OwnerId).First().Value;

            try
            {
                string DbPath   = "";
                string FilePath = "";
                string fileName = $"{Guid.NewGuid().ToString()}{ext}";
                if (input.ParentId == 0)
                {
                    FilePath = Path.Combine(StorageDirectory, user.Username, fileName);
                    DbPath   = Path.Combine(AppConsts.StorageDirectory, user.Username, fileName);
                }
                else
                {
                    var parent = await _fileManager.GetAsync(input.ParentId);

                    FilePath = Path.Combine(_env.WebRootPath, parent.Path, fileName);
                    DbPath   = Path.Combine(parent.Path, fileName);
                }

                byte[] buffer;

                if (user.Account.Type == AccountTypes.Free)
                {
                    buffer = new byte[16 * 1024];
                }
                else
                {
                    buffer = new byte[10240 * 1024];
                }


                using (FileStream output = System.IO.File.Create(FilePath))
                {
                    using (Stream sm = input.File.OpenReadStream())
                    {
                        long totalReadBytes = 0;
                        int  readBytes;

                        while ((readBytes = sm.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            await output.WriteAsync(buffer, 0, readBytes);

                            totalReadBytes += readBytes;
                            double percent = Math.Round(100 * (double)totalReadBytes / input.File.Length);
                            await _hub.Clients.Client(connId).SendUploadPercent(input.Uid, percent);
                        }
                    }
                }

                fileEntity.Path = DbPath;
                await _fileManager.CreateAsync(fileEntity);

                return(new JsonResult(new ResponseModel(message: "Succesfully uploaded")));
            }
            catch (Exception ex)
            {
                if (fileEntity.Id != 0)
                {
                    await _fileManager.DeleteAsync(fileEntity);
                }
                return(new JsonResult(new ResponseModel(message: "Error while uploading file", code: HttpStatusCode.BadRequest, success: false,
                                                        errors: new List <string> {
                    "Something went wrong"
                })));
            }
        }
示例#24
0
        public async Task UploadNewFileAsync(UploadFileDto dto)
        {
            var providers = GetScopeDbContext();

            var _dbContext = providers.DbContext;

            /*
             * 1. split to file peaces by the default max file peace size
             * 2. Get all the users, who have enough free space to store one peace and online
             * 3. Store all file peace with these users by the following:
             * 4. Calculate redundancy value. e.g.: 10 active phones, 30 pieces, 10% redundancy
             *                 => all phone stores 3 by default, and 3 phone stores 3 more (10%)
             * 5. Store the additional file peaces with other phones (not the same duplicated)
             * 6. add the file to the db
             * 7. add the file peaces to the db
             * 8. save db
             */

            // todo implement upload flow

            var uploaderUser = await _userService.GetUserById(dto.UserToken1);

            var chunks = dto.FileBytes.Chunk(_fileSettings.FilePeaceMaxSize);
            //var redundancy = (double) _fileSettings.RedundancyPercentage / 100; // e.g. 0.1

            var freeUsers = await _userService.GetOnlineUsersInNetworkWhoHaveEnoughFreeSpace(
                _fileSettings.FilePeaceMaxSize,
                uploaderUser.NetworkId.Value);

            if (freeUsers.Count == 0)
            {
                throw new OperationFailedException(
                          message: "There is no enough space to save this item",
                          statusCode: HttpStatusCode.PreconditionFailed,
                          webSocket: null);
            }

            var chunksAndIds = chunks.Select(x => (Bytes: x.Bytes, Id: Guid.NewGuid(), OrderNumber: x.OrderNumber));

            chunks = null;

            var fileEntity = new VirtualFileEntity
            {
                NetworkId    = uploaderUser.NetworkId.Value,
                Created      = DateTime.Now,
                FileId       = Guid.NewGuid(),
                FileName     = dto.FileName,
                FileSize     = dto.FileBytes.Length,
                LastModified = DateTime.Now,
                MimeType     = dto.MimeType,
                UploadedBy   = uploaderUser.Token1,
                IsConfirmed  = false
            };

            fileEntity = (await _dbContext.VirtualFile.AddAsync(fileEntity)).Entity;

            var tmpToAddIds = new List <(VirtualFilePieceEntity FIlePieceEntity, byte[] Bytes)>();

            foreach (var chunksAndId in chunksAndIds)
            {
                var filePeaceEntity = new VirtualFilePieceEntity
                {
                    FilePieceId   = chunksAndId.Id,
                    FileId        = fileEntity.FileId,
                    FilePieceSize = chunksAndId.Bytes.Length,
                    OrderNumber   = chunksAndId.OrderNumber,
                    IsConfirmed   = false
                };

                var entity = (await _dbContext.VirtualFilePiece.AddAsync(filePeaceEntity)).Entity;

                tmpToAddIds.Add((entity, chunksAndId.Bytes));
            }

            await _dbContext.SaveChangesAsync();

            chunksAndIds = null;

            chunksAndIds = tmpToAddIds.Select(x => (
                                                  Bytes: x.Bytes,
                                                  Id: x.FIlePieceEntity.FilePieceId,
                                                  OrderNumber: x.FIlePieceEntity.OrderNumber));


            var chunksAndIdsWithRedundancy = AddRedundancy(chunksAndIds.ToArray(), _fileSettings.RedundancyPercentage);

            chunksAndIds = null;

            var relation = new Dictionary <UserEntity, List <(byte[] bytes, Guid Id, int OrderNumber)> >();

            foreach (var freeUser in freeUsers)
            {
                relation.Add(freeUser, new List <(byte[] Bytes, Guid Id, int OrderNumber)>());
            }

            foreach (var fileBytesChunk in chunksAndIdsWithRedundancy)
            {
                var haveTheFewestAssociated = relation.FirstOrDefault(re => re.Value.Count == relation.Min(x => x.Value.Count));

                int tryNumber = 0;

                while (haveTheFewestAssociated.Value.Contains(fileBytesChunk) && tryNumber < 1000)
                {
                    var tmp = relation.ToArray();

                    haveTheFewestAssociated = tmp[_random.Next(tmp.Length)];

                    tryNumber++;
                }

                if (tryNumber < 1000)
                {
                    haveTheFewestAssociated.Value.Add(fileBytesChunk);
                }
            }

            chunksAndIdsWithRedundancy = null;

            #region Debug

            //byte[] outp = new byte[fileEntity.FileSize];
            //int i = 0;
            //foreach (var item in chunksAndIds.OrderBy(x => x.OrderNumber).ToList())
            //{
            //    foreach (var itemByte in item.Bytes)
            //    {
            //        outp[i] = itemByte;
            //        i++;
            //    }
            //}

            //bool isEqal = true;
            //for (int j = 0; j < outp.Length; j++)
            //{
            //    if (dto.FileBytes[j] != outp[j])
            //    {
            //        isEqal = false;
            //    }
            //}

            //if (!isEqal)
            //{
            //    throw new ApplicationException("The two array size are not the same");
            //}

            #endregion


            foreach (var relationItem in relation)
            {
                foreach (var filePeace in relationItem.Value)
                {
                    //todo no need for await, because i want to send immediately to all phones and lock is applied
                    _webSocketHandler
                    .SendFilePeaceToUser(
                        fileBytes: filePeace.bytes,
                        user: relationItem.Key.Token1,
                        filePeaceId: filePeace.Id,
                        networkId: uploaderUser.NetworkId.Value);
                }
            }

            relation = null;

            providers.Scope.Dispose();

            _logger.LogInformation("SUCCESS. All file has been prepared to sent.");
        }
示例#25
0
 public void Post([FromForm] UploadFileDto dto, [FromServices] IUploadFileCommand command)
 {
     _executor.ExecuteCommand(command, dto);
 }
        public async Task <ResponseResult <dynamic> > Upload([FromServices] IWebHostEnvironment environment)
        {
            var    data = new ResponseResult <dynamic>();
            string path = string.Empty;

            IFormFileCollection files = null;

            try
            {
                files = Request.Form.Files;
            }
            catch (Exception)
            {
                files = null;
            }

            if (files == null || !files.Any())
            {
                data.Message = nameof(BusinessCode.Image_Empty);
                data.Code    = BusinessCode.Image_Empty;
                return(data);
            }
            //格式限制


            string folderpath = Path.Combine(environment.WebRootPath, _uploadOptions.UploadFilePath);

            if (!System.IO.Directory.Exists(folderpath))
            {
                System.IO.Directory.CreateDirectory(folderpath);
            }

            if (files.Any(c => _uploadOptions.AllowedFileTypes?.Contains(c.ContentType.ToLower()) == true))
            {
                if (files.Sum(c => c.Length) <= _uploadOptions.UploadLimitSize)
                {
                    //foreach (var file in files)
                    var    file    = files.FirstOrDefault();
                    string strpath = Path.Combine(_uploadOptions.UploadFilePath, DateTime.Now.ToString("MMddHHmmss") + file.FileName);
                    path = Path.Combine(environment.WebRootPath, strpath);
                    string        md5Code = string.Empty;
                    UploadFileDto uploadFileDto;
                    int           uploadFileId = 0;
                    using (var stream = file.OpenReadStream())
                    {
                        md5Code       = GetFileMD5(stream);
                        uploadFileDto = await _uploadService.Get <UploadFileDto>(f => f.MD5Code == md5Code);

                        if (uploadFileDto == null)
                        {
                            using (var filestream = System.IO.File.Create(path))
                            {
                                await file.CopyToAsync(filestream);
                            }
                            uploadFileDto = new UploadFileDto
                            {
                                MD5Code   = md5Code,
                                RUrl      = strpath.Replace("\\", "/"),
                                Filename  = file.FileName,
                                Extention = Path.GetExtension(file.FileName).ToLower()
                            };

                            uploadFileId = (await _uploadService.AddOrUpdate <UploadFileDto, int>(uploadFileDto)).Id;
                        }
                        else
                        {
                            uploadFileId = uploadFileDto.Id;
                        }
                        strpath = UriCombine(Request.GetHostUri(), uploadFileDto.RUrl);
                        //strpath = uploadFileDto.RUrl;
                    }

                    data = new ResponseResult <dynamic>()
                    {
                        Data = new { url = strpath, id = uploadFileId }
                    };
                    return(data);
                }
                else
                {
                    data.Message = nameof(BusinessCode.Image_Size_Error);;
                    data.Code    = BusinessCode.Image_Size_Error;
                    return(data);
                }
            }
            else

            {
                data.Message = nameof(BusinessCode.Image_Type_Error);
                data.Code    = BusinessCode.Image_Type_Error;
                return(data);
            }
        }
示例#27
0
        public PageActionResult UploadArticelFile([FromForm] UploadFileDto model)
        {
            PageActionResult           operateResult = new PageActionResult();
            List <UploadFileViewModel> filelist      = new List <UploadFileViewModel>();

            try
            {
                foreach (var formFile in model.Files)
                {
                    if (formFile.Length > 0)
                    {
                        string time    = DateTime.Now.ToString("yyyyMMddHHmmss");
                        string fileDir = Path.Combine("wwwroot", "Upload", "File", "Article", time);
                        if (!Directory.Exists(fileDir))
                        {
                            Directory.CreateDirectory(fileDir);
                        }
                        string filePath = Path.Combine(fileDir, formFile.FileName);
                        string fileExt  = Path.GetExtension(formFile.FileName);
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            formFile.CopyTo(stream);
                        }
                        if (ImageHelper.IsWebImage(formFile.FileName))
                        {
                            string      thumbConfig = "340x200";
                            ImageFormat imgFormat;
                            #region 图片格式
                            if (string.Compare(fileExt, ".jpg", true) == 0 || string.Compare(fileExt, ".jpeg", true) == 0)
                            {
                                imgFormat = ImageFormat.Jpeg;
                            }
                            else if (string.Compare(fileExt, ".gif", true) == 0)
                            {
                                imgFormat = ImageFormat.Gif;
                            }
                            else if (string.Compare(fileExt, ".bmp", true) == 0)
                            {
                                imgFormat = ImageFormat.Bmp;
                            }
                            else if (string.Compare(fileExt, ".ico", true) == 0)
                            {
                                imgFormat = ImageFormat.Icon;
                            }
                            else
                            {
                                imgFormat = ImageFormat.Png;
                            }
                            #endregion
                            #region 生成缩略图

                            string[] thumbConfigSizes = thumbConfig.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string thumbConfigSize in thumbConfigSizes)
                            {
                                try
                                {
                                    string[] thumbSizeInfo = thumbConfigSize.Split(new string[] { "x" }, StringSplitOptions.RemoveEmptyEntries);
                                    if (thumbSizeInfo.Length < 2)
                                    {
                                        continue;
                                    }
                                    int width  = XConvert.ToInt32(thumbSizeInfo[0], 0);
                                    int height = XConvert.ToInt32(thumbSizeInfo[1], 0);
                                    if (width <= 0 || height <= 0)
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        string thumbSavePath = FileStoreUtil.GenerateThumbnailSavePath(filePath, width, height);
                                        ImageHelper.BuildThumbnail(filePath, thumbSavePath, imgFormat, width, height, true);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogHelper.WriteLog_LocalTxt(ex.ToJson());
                                }
                            }

                            #endregion
                        }

                        UploadFileViewModel file = new UploadFileViewModel
                        {
                            ArticleId = model.ArticleId,
                            FileName  = formFile.FileName,
                            FileExt   = fileExt,
                            Path      = Vars.FILESTORE_SITE + "/Upload/File/Article/" + time + @"/" + formFile.FileName,
                            Thumb     = Vars.FILESTORE_SITE + "/Upload/File/Article/" + time + @"/thumbs_" + Path.GetFileNameWithoutExtension(formFile.FileName) + @"/340_200" + fileExt,
                            Directory = time//文件所在目录
                        };
                        filelist.Add(file);
                    }
                }
                operateResult.Data    = new { List = filelist };
                operateResult.Result  = PageActionResultType.Success;
                operateResult.Message = "上传成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog_LocalTxt(ex.ToJson());
                operateResult.Result  = PageActionResultType.Failed;
                operateResult.Message = "上传失败";
            }
            return(operateResult);
        }
示例#28
0
 public async Task <IActionResult> UploadFile([FromForm] UploadFileDto uploadFileDto)
 {
     return(Ok(await _mediator.Send(uploadFileDto)));
 }