将图像从Webapi上传到Blob存储时,如何验证扩展名和图片大小?

问题描述 投票:0回答:1

我有以下代码来上传图片,使用GUID重命名并更新POCO个人资料图片URL。

但是我需要一些额外的验证1.仅允许png文件2.最大200x200(图片应为正方形)

但是我不确定如何满足这两个要求。

 [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);
            }            
        }
c# asp.net .net asp.net-web-api azure-blob-storage
1个回答
0
投票

尝试使用以下代码:

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
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.