0

I have the following code to upload a picture, rename it with a guid and updating a POCO profile picture URL.

However I need some extra validation 1. Only png files should be allowed 2. Max 200x200 ( and picture should be squared)

However I am not sure how to do this 2 requirements.

 [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);
            }            
        }
Luis Valencia
  • 32,619
  • 93
  • 286
  • 506
  • Possible duplicate of [How to get the image dimension from the file name](https://stackoverflow.com/questions/6455979/how-to-get-the-image-dimension-from-the-file-name) and [How to find the extension of a file?](https://stackoverflow.com/questions/1886866/how-to-find-the-extension-of-a-file) – Cid Oct 16 '19 at 13:24
  • not a duplicate because using the Azure Blob Storage SDK is a different story to the mentioned questions/answers. – Luis Valencia Oct 16 '19 at 13:36
  • 1
    You check it **before** uploading. There is no file in a blob, only some binary datas – Cid Oct 16 '19 at 13:37

1 Answers1

1

try to play with the following code:

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
        }
    }
}
Ali Keserwan
  • 217
  • 1
  • 4