Exemplo n.º 1
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log,
            ExecutionContext context)
        {
            // get the config
            _config = new ConfigurationBuilder()
                      .SetBasePath(context.FunctionAppDirectory)
                      .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                      .AddEnvironmentVariables()
                      .Build();


            // Get request body
            var body = await new StreamReader(req.Body).ReadToEndAsync();

            if (body == null)
            {
                return(new BadRequestObjectResult("No body found"));
            }

            // deserialize the payload
            var data = Newtonsoft.Json.JsonConvert.DeserializeObject <ImageUpload>(body);

            if (data.Imageb64 == null)
            {
                return(new BadRequestObjectResult("No 'imageb64' property found in body"));
            }

            // get the base64 image
            var img = data.Imageb64;

            // convert to byte array
            byte[] buffer = new byte[0];
            try
            {
                buffer = Convert.FromBase64String(img.ToString());
            }
            catch
            {
                return(new BadRequestObjectResult("unable to read 'imageb64' data"));
            }

            // Upload to blob storage
            if (buffer.Length == 0)
            {
                return(new BadRequestObjectResult("unable to upload buffer with length of 0"));
            }
            else
            {
                log.LogInformation($"Received image of size {buffer.Length} bytes");

                // add the image to blob storage and get the url
                string url = await BlobManager.AddOriginalImage(buffer);

                // add the image to table and get the id
                var imageEntity = await TableManager.AddOriginalImage(url);

                // send the image entity to event grid
                await EventGridManager.SendNewImageEvent(imageEntity);

                // return the details to the user
                return(new OkObjectResult(new ImageUploadResult {
                    Id = imageEntity.RowKey, Url = url
                }));
            }
        }