Как я могу проверить расширение и размер изображения при загрузке изображения из webapi в хранилище BLOB-объектов? - PullRequest
0 голосов
/ 16 октября 2019

У меня есть следующий код для загрузки изображения, переименования его с помощью guid и обновления URL-адреса изображения профиля POCO.

Однако мне нужна дополнительная проверка 1. Должны быть разрешены только файлы png 2. Максимум 200x200(и изображение должно быть в квадрате)

Однако я не уверен, как выполнить это 2 требования.

 [HttpPut]
        public async Task<IHttpActionResult> UpdateUser(User user)
        {
            var telemetry = new TelemetryClient();
            try
            {
                //First we validate the model
                var userStore = CosmosStoreHolder.Instance.CosmosStoreUser;
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                //Then we validate the content type
                if (!Request.Content.IsMimeMultipartContent("form-data"))
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                //Initalize configuration settings
                var accountName = ConfigurationManager.AppSettings["storage:account:name"];
                var accountKey = ConfigurationManager.AppSettings["storage:account:key"];
                var profilepicturecontainername = ConfigurationManager.AppSettings["storage:account:profilepicscontainername"];


                //Instance objects needed to store the files
                var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer imagesContainer = blobClient.GetContainerReference(profilepicturecontainername);
                var provider = new AzureStorageMultipartFormDataStreamProvider(imagesContainer);

                //Try to upload file
                try
                {
                    await Request.Content.ReadAsMultipartAsync(provider);
                }
                catch (Exception ex)
                {
                    string guid = Guid.NewGuid().ToString();
                    var dt = new Dictionary<string, string>
                    {
                        { "Error Lulo: ", guid }
                    };
                    telemetry.TrackException(ex, dt);
                    return BadRequest($"Error Lulo. An error has occured. Details: {guid} {ex.Message}: ");
                }

                // Retrieve the filename of the file you have uploaded
                var filename = provider.FileData.FirstOrDefault()?.LocalFileName;
                if (string.IsNullOrEmpty(filename))
                {
                    string guid = Guid.NewGuid().ToString();
                    var dt = new Dictionary<string, string>
                    {
                        { "Error Lulo: ", guid }
                    };

                    return BadRequest($"Error Lulo. An error has occured while uploading your file. Please try again.: {guid} ");
                }

                //Rename file
                CloudBlockBlob blobCopy = imagesContainer.GetBlockBlobReference(user.Id+".png");
                if (!await blobCopy.ExistsAsync())
                {
                    CloudBlockBlob blob = imagesContainer.GetBlockBlobReference(filename);

                    if (await blob.ExistsAsync())
                    {
                        await blobCopy.StartCopyAsync(blob);
                        await blob.DeleteIfExistsAsync();
                    }
                }

                user.ProfilePictureUrl = blobCopy.Name;

                var result = await userStore.UpdateAsync(user);
                return Ok(result);
            }
            catch (Exception ex)
            {
                string guid = Guid.NewGuid().ToString();
                var dt = new Dictionary<string, string>
                {
                    { "Error Lulo: ", guid }
                };

                telemetry.TrackException(ex, dt);
                return BadRequest("Error Lulo: " + guid);
            }            
        }

1 Ответ

1 голос
/ 16 октября 2019

попробуйте поиграть со следующим кодом:

foreach (MultipartFileData file in provider.FileData)
{

    var fileName = file.Headers.ContentDisposition.FileName.Trim('\"').Trim();
    if (fileName.EndsWith(".png"))
    {
        var img = Image.FromFile(file.LocalFileName);
        if (img.Width == 200 && img.Height == 200)
        {
            //here is ur logic
        }
    }
}
...