コード例 #1
0
        [RequestSizeLimit(30000000)]  //TODO: 30 MB, should be put into the config.. some of the files might be large. We will add
        public async Task <ActionResult <ResourceResponse> > UploadResource(Guid organizationId, Guid encSystemId, string resourceName, IFormFile resource)
        {
            // TODO: Might want to handle multiple files upload at once.
            // restrict file types
            // check ext consistency between resourceId.ext and resource.ext
            // check for existing resourceId with different file type too

            if (!Path.HasExtension(resourceName))
            {
                throw GenerateResourceApiException(ResourceApiErrorCode.NoFileExtension);
            }

            if (resource == null || resource.Length == 0)
            {
                throw GenerateResourceApiException(ResourceApiErrorCode.InvalidFile);
            }

            int    extCount      = resourceName.Count(f => f == '.');
            string fileExtension = GetFullFileExtension(resource.FileName);

            if (extCount > 2)
            {
                throw GenerateResourceApiException(ResourceApiErrorCode.FileTypeNotSupported, fileExtension);
            }

            if (!fileExtension.Replace(".", "").All(Char.IsLetterOrDigit))
            {
                throw GenerateResourceApiException(ResourceApiErrorCode.InvalidChar, fileExtension);
            }

            var temp = GetFullFileExtension((resourceName));

            if (fileExtension != GetFullFileExtension(resourceName))
            {
                throw GenerateResourceApiException(ResourceApiErrorCode.FileExtensionMismatch);
            }

            if (!_adapter.FileSupported(fileExtension))
            {
                throw GenerateResourceApiException(ResourceApiErrorCode.FileTypeNotSupported, fileExtension);
            }

            var isGuid = IsGuid(resourceName);

            if (!isGuid)
            {
                throw GenerateResourceApiException(ResourceApiErrorCode.InvalidGuid, resourceName);
            }

            var uploadedFileUrl = String.Empty;
            var path            = ResourceUtility.CreatePathName(organizationId.ToString(), encSystemId.ToString(), resourceName.ToLower());

            if (await _adapter.DoesExist(path))
            {
                throw GenerateResourceApiException(ResourceApiErrorCode.FileAlreadyExists, resourceName);
            }

            using (var stream = resource.OpenReadStream())
            {
                uploadedFileUrl = await _adapter.Upload(path, stream);
            }

            string url = ConvertStorageUrlToResourceApiUrl(organizationId, uploadedFileUrl);

            _logger.Log(LogLevel.Information, "File {0} uploaded successfully.", url);

            return(Ok(new ResourceResponse(url)));
        }