DEV Community

Elio Struyf
Elio Struyf

Posted on • Originally published at eliostruyf.com on

Parse multipart/form-data in Azure Function

While working on an internal Azure Static Web Site project, I needed to upload CSV files to an Azure Function to import data to Cosmos DB.

When uploading a file to your API, the multipart/form-data content-type is used. The body’s format looks a bit “special” as it requires some parsing to get each file.

-----WebKitFormBoundaryXvnFih9Jfw9ZdQNB
Content-Disposition: form-data; name': '"file"; filename="2020-9-2-localization.csv"
Content-Type: text/csv
id,name
test1,test1
test2,test2
------WebKitFormBoundaryXvnFih9Jfw9ZdQNB--
Enter fullscreen mode Exit fullscreen mode

Like the previous article about parsing application/x-www-form-urlencoded in Azure Function, this content type is something you must parse yourself as well.

To make it easier, you will have to install the following dependency to your project: npm i parse-multipart -S -E. The code looks like this:

import { AzureFunction, Context, HttpRequest } from "@azure/functions";
import * as multipart from 'parse-multipart';

const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
  const body = req.rawBody;
  // Retrieve the boundary id
  const boundary = multipart.getBoundary(req.headers["content-type"]);
  if (boundary) {
    const files: File[] = multipart.Parse(Buffer.from(body), boundary);

    if (files && files.length > 0) {
      // Do what you want to do with the file
    }

    context.res.status(200);
  } else {
    context.res.status(500).send("No file(s) found.");
  }
};
Enter fullscreen mode Exit fullscreen mode

I hope this helps you get started processing your uploaded files.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
anzhari profile image
Anzhari Purnomo

Recently facing this issue on my projects. I ended up writing an npm module for this: npmjs.com/package/@anzp/azure-func...

Hope it can help anybody struggling with this issue!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay