Пример #1
0
        public async Task AddFile(AddFileDto fileDto, int userId, int clientId)
        {
            var fileStorageRepository = DataContextManager.CreateRepository <IFileStorageRepository>();

            var parentFileStorage = await fileStorageRepository.GetById(fileDto.ParentId, userId, clientId);

            if (parentFileStorage == null || !parentFileStorage.IsDirectory)
            {
                throw new NotFoundException("File storage", fileDto.ParentId);
            }

            var fileName      = Path.GetFileNameWithoutExtension(fileDto.Name);
            var fileExtension = Path.GetExtension(fileDto.Name);

            var childFileStorages = await fileStorageRepository.GetByParentId(parentFileStorage.Id, userId, clientId);

            if (childFileStorages.Any(x => !x.IsDirectory && x.Name.Equals(fileName) &&
                                      x.Files.Any(y => y.IsActive && y.Extension.Equals(fileExtension))))
            {
                throw new FoundSameObjectException("File storage", fileName);
            }

            var owners = await _permissionHelper.GetOwners(parentFileStorage, userId, clientId);

            var sizeInfo = fileDto.Size.ToPrettySize();
            var blobName = Guid.NewGuid();

            var newFileStorage = new FileStorage
            {
                Name = fileName,
                ParentFileStorageId = parentFileStorage.Id,
                IsDirectory         = false,
                CreateDate          = DateTime.UtcNow,
                CreateById          = userId,
                ClientId            = owners.ClientId,
                OwnerId             = owners.OwnerId,
                IsActive            = true,
                Files = new List <Models.File>
                {
                    new Models.File
                    {
                        Extension        = fileExtension,
                        Size             = sizeInfo.Size,
                        SizeType         = sizeInfo.SizeType,
                        IsActive         = true,
                        CreateById       = userId,
                        CreateDate       = DateTime.UtcNow,
                        AzureBlobStorage = new AzureBlobStorage
                        {
                            BlobName = blobName
                        }
                    }
                }
            };

            await _azureBlobClient.UploadFile(_blobSettings.ContainerName, blobName.ToString(), fileDto.Content.ToByteArray());

            await fileStorageRepository.Add(newFileStorage);
        }
        public async Task <ActionResult> AddFile([FromBody] AddFileDto fileDto)
        {
            if (!IsAvailableOperation())
            {
                return(BadRequest());
            }


            await _fileStorageService.AddFile(fileDto, UserId, ClientId);

            AddLog(Enums.LogType.Create, LogMessage.CreateSuccessByNameMessage(LogMessage.FileEntityName, fileDto.Name, LogMessage.CreateAction, UserId));
            return(Ok());
        }
Пример #3
0
        private string SavePic(AddFileDto thisAttDto, out string saveFileName)
        {
            saveFileName = "";
            string fileExtension = Path.GetExtension(thisAttDto.old_filename).ToLower();    //取得文件的扩展名,并转换成小写
            string filepath      = $"/Upload/Attachment/{DateTime.Now.ToString("yyyyMM")}/";

            if (Directory.Exists(Server.MapPath(filepath)) == false)    //如果不存在就创建文件夹
            {
                Directory.CreateDirectory(Server.MapPath(filepath));
            }
            string virpath = filepath + Guid.NewGuid().ToString() + fileExtension; //这是存到服务器上的虚拟路径
            string mappath = Server.MapPath(virpath);                              //转换成服务器上的物理路径

            //FileStream fs = new FileStream(oldPath, FileMode.Open, FileAccess.ReadWrite);
            File.WriteAllBytes(mappath, thisAttDto.files as Byte[]);
            //  fileForm.SaveAs(mappath);//保存图片
            //fs.Close();
            saveFileName = virpath;
            return("");
        }
Пример #4
0
        private void SaveSession()
        {
            var type_id = Request.Form["type_id"];
            var name    = Request.Form["name"];
            var file    = Request.Files["attFile"];
            var attLink = Request.Form["attLink"];

            if (!string.IsNullOrEmpty(type_id) && !string.IsNullOrEmpty(name))
            {
                var objectId = Request.QueryString["object_id"];
                if (!string.IsNullOrEmpty(objectId))
                {
                    var thisDto = new AddFileDto();
                    if (type_id == ((int)DicEnum.ATTACHMENT_TYPE.ATTACHMENT).ToString())
                    {
                        if (file != null && file.ContentLength < (10 << 20))
                        {
                            //FileStream fs = new FileStream(Request.Form["old_file_path"], FileMode.Open, FileAccess.Read);

                            thisDto.type_id      = type_id;
                            thisDto.old_filename = file.FileName;
                            thisDto.new_filename = name;
                            thisDto.conType      = file.ContentType;
                            thisDto.Size         = file.ContentLength;
                            // thisDto.files = file;
                            Stream fileDataStream = file.InputStream;
                            byte[] buffur         = new byte[file.ContentLength];
                            fileDataStream.Read(buffur, 0, file.ContentLength);
                            //fs.Read(buffur, 0, (int)fs.Length);
                            //thisDto.old_file_path = Request.Form["old_file_path"];
                            //fs.Close();
                            thisDto.files = buffur;
                        }
                    }
                    else
                    {
                        thisDto.type_id      = type_id;
                        thisDto.old_filename = attLink;
                        thisDto.new_filename = name;
                        thisDto.files        = attLink;
                    }



                    var sesNum = Session[objectId + "_Att"] as List <AddFileDto>;
                    if (sesNum != null && sesNum.Count > 0)
                    {
                        sesNum.Add(thisDto);
                        Session[objectId + "_Att"] = sesNum;
                    }
                    else
                    {
                        Session[objectId + "_Att"] = new List <AddFileDto>()
                        {
                            thisDto
                        };
                        // 需要存四个属性,类型,原文件名,新文件名,类型,文件流
                    }
                }
            }
        }
Пример #5
0
        public async Task <MultiPartRequestDto> HandleMultiPartRequest(HttpRequest request)
        {
            if (!IsMultipartContentType(request.ContentType))
            {
                throw new Exception($"Expected a multipart request, but got {request.ContentType}");
            }

            var formAccumulator = new KeyValueAccumulator();

            var boundary = GetBoundary(
                MediaTypeHeaderValue.Parse(request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, request.Body);

            var section = await reader.ReadNextSectionAsync();

            var media = new List <AddFileDto>();

            while (section != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (HasFileContentDisposition(contentDisposition))
                    {
                        var processedMedia = await _fileService.ProcessStreamedFileAsync(section, contentDisposition);

                        var mediaDto = new AddFileDto
                        {
                            File          = processedMedia,
                            FileExtension = Path.GetExtension(contentDisposition.FileName.Value),
                        };
                        media.Add(mediaDto);
                    }
                    else if (HasFormDataContentDisposition(contentDisposition))
                    {
                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name).Value;
                        var encoding = GetEncoding(section);

                        using (var streamReader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
                        {
                            var value = await streamReader.ReadToEndAsync();

                            if (string.Equals(value, "undefined",
                                              StringComparison.OrdinalIgnoreCase))
                            {
                                value = string.Empty;
                            }

                            formAccumulator.Append(key, value);

                            if (formAccumulator.ValueCount >
                                int.MaxValue)
                            {
                                throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
                            }
                        }
                    }
                }

                section = await reader.ReadNextSectionAsync();
            }

            //request.Body.Position = 0;

            var formAccumulatorResults = formAccumulator.GetResults();
            var formValueProvider      = new FormValueProvider(
                BindingSource.Form,
                new FormCollection(formAccumulatorResults),
                CultureInfo.CurrentCulture);

            return(new MultiPartRequestDto
            {
                FormValueProvider = formValueProvider,
                File = media,
            });
        }