Send files to your server with axios

This will be a short post, but if you write Typescript or Javascript and use axios as an HTTP client, you might find yourself needing to send files to your server at some point.

You can install and use the form-data module if in a Node.js environment, and a short script to get you started is below. Note that you can append a string, ReadStream, or Buffer to the FormData instance, but in the script below we use a ReadStream from the fs module since the example shows how to send a file from the file system.

import fs from 'fs'
import axios from 'axios'
import FormData from 'form-data'

async function sendFile(filePath: string) {
  const form = new FormData()
  form.append('file', fs.createReadStream(filePath))
  const { data } = await``, form, {
    headers: form.getHeaders()
  return data