Пример #1
0
        public IHttpActionResult GetFileIdByExtension(string id)
        {
            try
            {
                if (id == null)
                {
                    throw new NsiArgumentException(FileTypeMessages.FileTypeInvalidArgument);
                }

                var result = _fileTypeManipulation.GetFileIdByExtension(id);

                if (result < 0)
                {
                    throw new NsiBaseException(string.Format(FileTypeMessages.FileTypeUpdateFailed));
                }

                return(Ok(result));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
Пример #2
0
        public async Task <IHttpActionResult> UploadFile(string fileName = "", string description = "")
        {
            //Check if submitted content is of MIME Multi Part Content with Form-data in it?
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                return(BadRequest("Could not find file to upload"));
            }
            //Read the content in a InMemory Muli-Part Form Data format
            var provider = await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider());

            //Get the first file
            var files        = provider.Files;
            var uploadedFile = files[0];

            fileName = Path.GetFileNameWithoutExtension(uploadedFile.Headers.ContentDisposition.FileName.Trim('"'));
            //Extract the file extention
            var extension = ExtractExtension(uploadedFile);
            //Get the file's content type
            var contentType = uploadedFile.Headers.ContentType.ToString();
            //create the full name of the image with the fileName and extension
            var imageName = string.Concat(fileName, extension);
            //Get the reference to the Blob Storage and upload the file there
            var storageConnectionString = "";

            string[] tokens        = extension.Split('.');
            string   extensionName = tokens[tokens.Length - 1];
            var      fileTypeId    = _fileTypeManipulation.GetFileIdByExtension(extensionName);

            if (this._azureActive.Equals("true"))
            {
                storageConnectionString = ConfigurationManager.AppSettings["azurestoragepath"];
                var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
                var blobClient     = storageAccount.CreateCloudBlobClient();
                var container      = blobClient.GetContainerReference("nsicontainer");
                container.CreateIfNotExists();
                var blockBlob = container.GetBlockBlobReference(imageName);
                blockBlob.Properties.ContentType = contentType;
                using (var fileStream = await uploadedFile.ReadAsStreamAsync()) //as Stream is IDisposable
                {
                    blockBlob.UploadFromStream(fileStream);
                }

                var document = new DocumentDomain
                {
                    DocumentId         = 0,
                    Name               = fileName,
                    Path               = blockBlob.Uri.ToString(),
                    FileSize           = blockBlob.StreamWriteSizeInBytes,
                    ExternalId         = Guid.NewGuid(),
                    LocationExternalId = blockBlob.Uri.ToString(),
                    DateCreated        = DateTime.Now,
                    StorageTypeId      = 1,
                    FileTypeId         = fileTypeId,
                    Description        = description
                };
                var result = _documentManipulation.CreateDocument(document);
                return(Ok(result));
            }
            else if (this._azureActive.Equals("false"))
            {
                var localFilePath = ConfigurationManager.AppSettings["localstoragepath"];
                var guid          = Guid.NewGuid();
                var fullPath      = $@"{localFilePath}\{fileName}{extension}";
                var fileSize      = 0;

                using (var fileStream = await uploadedFile.ReadAsStreamAsync())
                    using (var localFileStream = File.Create(fullPath))
                    {
                        fileStream.Seek(0, SeekOrigin.Begin);
                        fileStream.CopyTo(localFileStream);
                        fileSize = (int)fileStream.Length;
                    }

                if (!DocumentManipulation.IsSafe(fullPath))
                {
                    File.Delete(fullPath);
                    return(BadRequest("File contains malware"));
                }

                var document = new DocumentDomain
                {
                    DocumentId         = 0,
                    Name               = fileName,
                    Path               = fullPath,
                    FileSize           = fileSize,
                    ExternalId         = guid,
                    LocationExternalId = "",
                    DateCreated        = DateTime.Now,
                    StorageTypeId      = 2,
                    FileTypeId         = fileTypeId,
                    Description        = description
                };

                var result = _documentManipulation.CreateDocument(document);

                return(Ok(result));
            }
            else
            {
                return(BadRequest(DocumentMessages.UnexpectedProblem));
            }
        }