DEV Community

Cover image for Parse multipart/form-data in Azure Functions
Anzhari Purnomo
Anzhari Purnomo

Posted on

Parse multipart/form-data in Azure Functions

Recently I have to work with quite a lot of Azure based services. I had to write a Function that accept a file upload. Which then I realized, that Azure Functions does not have built in mechanism or API to handle file upload easily.

I ended up writing an npm module for this issue: https://www.npmjs.com/package/@anzp/azure-function-multipart

An example on how to use it:

import { AzureFunction, Context, HttpRequest } from "@azure/functions";
import parseMultipartFormData from "@anzp/azure-function-multipart";

const httpTrigger: AzureFunction = async function (
  context: Context,
  req: HttpRequest
): Promise<void> {
  const { fields, files } = await parseMultipartFormData(req);
  context.log("HTTP trigger function processed a request.");
  const name = req.query.name || (req.body && req.body.name);
  const responseMessage = {
    fields,
    files,
  };

  context.res = {
    // status: 200, /* Defaults to 200 */
    body: responseMessage,
  };
};

export default httpTrigger;
Enter fullscreen mode Exit fullscreen mode

Example client request using CURL:

curl --request POST \
  --url http://localhost:7071/api/HttpTrigger1 \
  --header 'Content-Type: multipart/form-data; boundary=---011000010111000001101001' \
  --form update=false \
  --form collection=@/Users/anzhari/masterdata/managements.json
Enter fullscreen mode Exit fullscreen mode

This is the example reponse received on the client:

{
  "fields": [
    {
      "fieldname": "update",
      "value": "false",
      "fieldnameTruncated": false,
      "valueTruncated": false,
      "encoding": "7bit",
      "mimetype": "text/plain"
    }
  ],
  "files": [
    {
      "fieldname": "file",
      "bufferFile": {
        "type": "Buffer",
        "data": [
          91,
          10,
          ...
          10,
          93
        ]
      },
      "filename": "managements.json",
      "encoding": "7bit",
      "mimetype": "application/json"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Hope it can help anybody struggling with this issue!

Top comments (1)

Collapse
 
mikeainoz profile image
Mike Allen

Hi Anzhari, this is a great idea, I've always struggled with multiprat/form-data. IN mt current function I'm using this package. I'm submitting to table storage.
Trying to do it like this (pardon my TypeScript):
tableService.insertEntity(tableName,{...thisKey,...fields},{ echoContent: true }
This is not working, I assume because fields is an array and not an object. I'm going to fix this with my middling Typescript skills, and I'm sure I will learn something.
I was wondering if an option to return an object for fields is a possibility, so that spread can be used? What do you think?