コード例 #1
0
            /// <summary>
            /// Initializes the BLOB.
            /// </summary>
            /// <param name="blobName">Name of the BLOB.</param>
            private async Task <AppendBlobClient> InitializeBlob(string blobName, BlobContainerClient blobContainer, string contentType, CancellationToken cancellationToken)
            {
                var appendBlob = blobContainer.GetAppendBlobClient(blobName);

                var blobExits = await appendBlob.ExistsAsync(cancellationToken).ConfigureAwait(false);

                if (blobExits)
                {
                    return(appendBlob);
                }

                var blobCreateOptions = new Azure.Storage.Blobs.Models.AppendBlobCreateOptions();
                var httpHeaders       = new Azure.Storage.Blobs.Models.BlobHttpHeaders()
                {
                    ContentType     = contentType,
                    ContentEncoding = Encoding.UTF8.WebName,
                };

                blobCreateOptions.HttpHeaders = httpHeaders;
                blobCreateOptions.Metadata    = _blobMetadata;  // Optional custom metadata to set for this append blob.
                blobCreateOptions.Tags        = _blobTags;      // Options tags to set for this append blob.

                await appendBlob.CreateIfNotExistsAsync(blobCreateOptions, cancellationToken).ConfigureAwait(false);

                return(appendBlob);
            }
コード例 #2
0
ファイル: FilesController.cs プロジェクト: mdesenfants/shost
        public async Task <IActionResult> Post(List <IFormFile> files)
        {
            foreach (var file in files)
            {
                if (file == null)
                {
                    throw new Exception("File is null");
                }
                if (file.Length == 0)
                {
                    throw new Exception("File is empty");
                }

                var headers = new Azure.Storage.Blobs.Models.BlobHttpHeaders()
                {
                    ContentType        = file.ContentType,
                    ContentDisposition = file.ContentDisposition
                };

                var stream = file.OpenReadStream();

                await Container.UploadEncryptedAsync(file.FileName, stream, headers);
            }

            return(Accepted());
        }
コード例 #3
0
        public async Task <IActionResult> Store(string clientId, string container = null, string fileName = null, DateTime?expirationDate = null, List <IFormFile> files = null)
        {
            if (files.Count == 0)
            {
                return(Json("No files uploaded"));
            }

            string origFileName = null;

            IdentityHandler.InternalIdentity identity = null;
            // Store a file and return static url to data
            if (!string.IsNullOrEmpty(container))
            {
                // Private container
                identity = await IdentityHandler.GetIdentityAsync(clientId, container);

                if (identity == null)
                {
                    Response.StatusCode = 403;
                    return(Json("Could not retrieve Identity data"));
                }
                if (!identity.Data.allowFileWrite)
                {
                    Response.StatusCode = 403;
                    return(Json("No write-access"));
                }
            }
            else
            {
                // Public 'container'. This generates a random file name and will put it in a container which cannot be listed/deleted
                container    = "public";
                origFileName = fileName ?? files.FirstOrDefault()?.FileName;
                fileName     = Guid.NewGuid().ToString();
            }

            // Upload
            BlobContainerClient azureContainerClient = new BlobContainerClient(Startup.Configuration.GetConnectionString("StorageConnectionString"), Startup.Configuration.GetValue <string>("StorageContainer"));
            var tkContainer = await GetStorageContainerData(azureContainerClient, container, true);

            if (tkContainer == null)
            {
                Response.StatusCode = 500;
                return(Json("Internal error"));
            }

            var filesUploaded = new List <object>();


            foreach (var file in files)
            {
                if (container == "public" || (string.IsNullOrEmpty(fileName) && string.IsNullOrEmpty(file.FileName)))
                {
                    fileName = GetRandomString(); // Generate a random short code as filename
                }
                else if (string.IsNullOrEmpty(fileName) && !string.IsNullOrEmpty(file.FileName))
                {
                    fileName = file.FileName;
                }

                fileName = fileName.Replace("\\", "").Replace("\"", "").Replace("..", "").Replace(":", "");
                if (fileName.StartsWith("/"))
                {
                    fileName = fileName.Substring(1);
                }

                var uploadFileName = tkContainer.Code + "/" + GetRandomString() + "_" + fileName;
                var fileBlob       = azureContainerClient.GetBlobClient(uploadFileName);

                var ext     = Path.GetExtension(fileName).ToLower();
                var headers = new Azure.Storage.Blobs.Models.BlobHttpHeaders();
                headers.ContentDisposition = "inline";
                headers.CacheControl       = "public, max-age=31536000";

                var contentType = GetContentType(origFileName ?? fileName);
                if (contentType == null)
                {
                    // Only allow to download this file
                    headers.ContentDisposition = "attachment; filename=\"" + fileName + "\"";
                    headers.ContentType        = "application/octet-stream";
                }
                else
                {
                    headers.ContentType = contentType;
                }

                using (var fileStream = file.OpenReadStream())
                {
                    await fileBlob.UploadAsync(fileStream, new Azure.Storage.Blobs.Models.BlobUploadOptions()
                    {
                        HttpHeaders = headers,
                        Metadata    = new Dictionary <string, string>
                        {
                            { "UploadedByClientId", clientId },
                            { "UploadedByIdentifier", identity?.Data?.publicIdentifier ?? "- Unknown -" },
                            { "UploadedByIP", Request.HttpContext.Connection.RemoteIpAddress.ToString() }
                        }
                    });
                }

                filesUploaded.Add(new
                {
                    FileName    = fileName,
                    Url         = Startup.Configuration.GetValue <string>("StorageUrlPrefix") + uploadFileName,
                    ContentType = headers.ContentType
                });

                fileName = null; // We only allow a custom filename passed by the first upload
            }

            return(Json(filesUploaded));
        }