Search code examples
c#azurehttppowerapps

Azure function not working properly ?


I have an azure function which takes an input file using multi form like this -

    public static class function
{
    [FunctionName("Function1")]
    public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log,string imagename)
    {


        // parse query parameter
        string name = req.GetQueryNameValuePairs()
            .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
            .Value;

        // Get request body
        dynamic data = await req.Content.ReadAsAsync<object>();

        // Set name to query string or body data
        name = name ?? data?.name;


       log.Info("C# HTTP trigger function processed a request.");


        return name == null
            ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
            : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
    }

As you can see at the moment I am not doing anything with the file. I am trying to get it run first.

My swagger file looks like this :

        {
 "swagger": "2.0",
  "info": {
  "version": "1.0.0",
  "title": "Testfunction"
  },
  "host": "Testfunction.azurewebsites.net",
 "paths": {
   "/api/Function1": {
  "post": {
    "tags": [
      "Function1"
    ],
    "operationId": "UploadImage",
    "consumes": [
      "multipart/form-data"
    ],
    "produces": [
      "application/json",
      "text/json",
      "application/xml",
      "text/xml"
    ],
    "parameters": [
      {
        "name": "file",
        "in": "formData",
        "required": true,
        "type": "file",
        "x-ms-media-kind": "image"
      },
      {
        "name": "fileName",
        "in": "query",
        "required": false,
        "type": "string"
      }
    ],
    "responses": {
      "200": {
        "description": "Saved successfully",
        "schema": {
          "$ref": "#/definitions/UploadedFileInfo"
        }
      },
      "400": {
        "description": "Could not find file to upload"
      }
    },
    "summary": "Image Upload",
    "description": "Image Upload"
  }
}},
"definitions": {
"UploadedFileInfo": {
  "type": "object",
  "properties": {
    "FileName": {
      "type": "string"
    },
    "FileExtension": {
      "type": "string"
    },
    "FileURL": {
      "type": "string"
    },
    "ContentType": {
      "type": "string"
    }
  }
}

},
  "securityDefinitions": {
"AAD": {
  "type": "oauth2",
  "flow": "accessCode",
  "authorizationUrl": "https://login.windows.net/common/oauth2/authorize",
  "tokenUrl": "https://login.windows.net/common/oauth2/token",
  "scopes": {}
   }
 },
 "security": [
  {
   "AAD": []
  }
],
"tags": []

}

I have configured the Auth0 properly but when I try to run this in Powerapps, it returns with unknown error as the response.

I am trying to send an image to the azure function with which I want to convert it to PDF. How can I do this?


Solution

  • According to your code, it seems that you are using the precompiled functions. I found your HttpTrigger function code does not match the swagger file you provided. For a simple way, I just use the Azure Portal and created my HttpTrigger function as follow:

    run.csx:

    using System.Net;
    
    public static async Task<HttpResponseMessage> Run(HttpRequestMessage request, TraceWriter log)
    {
        //Check if the request contains multipart/form-data.
        if (!request.Content.IsMimeMultipartContent())
        {
            return request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
        }
        
        //The root path where the content of MIME multipart body parts are written to
        string root = Path.Combine(System.Environment.GetEnvironmentVariable("HOME"), @"site\wwwroot\HttpTriggerCSharp1\");
        var provider = new MultipartFormDataStreamProvider(root);
    
        // Read the form data
        await request.Content.ReadAsMultipartAsync(provider);
    
        List<UploadedFileInfo> files = new List<UploadedFileInfo>();
        // This illustrates how to get the file names.
        foreach (MultipartFileData file in provider.FileData)
        {   
            var fileInfo = new FileInfo(file.Headers.ContentDisposition.FileName.Trim('"'));
            files.Add(new UploadedFileInfo()
            {
                FileName = fileInfo.Name,
                ContentType = file.Headers.ContentType.MediaType,
                FileExtension = fileInfo.Extension,
                FileURL = file.LocalFileName
            });
        }
        return request.CreateResponse(HttpStatusCode.OK, files, "application/json");
    }
    
    public class UploadedFileInfo
    {
        public string FileName { get; set; }
        public string FileExtension { get; set; }
        public string FileURL { get; set; }
        public string ContentType { get; set; }
    }
    

    Note: The MIME multipart body parts are stored under your temp folder. You could retrieve the temp file full path via file.LocalFileName, then use the related library to process the conversion, then save the PDF file(s) and remove the temp file(s), then return the converted file(s) to the client.

    Test:

    enter image description here

    Additionally, I would recommend you store your files under Azure Blob Storage. And you could refer to this official toturial for getting started with it.