Skip to main content

Uploading Files Using node-fetch

Easily upload files to your system with node-fetch, a lightweight module that brings window.fetch to Node.js. This guide demonstrates how to upload files using node-fetch and TypeScript.


Prerequisites

Ensure you have node-fetch and form-data installed in your project:

npm install node-fetch form-data

Uploading a File

Here’s a simple script to upload a file to the Zigned REST API using node-fetch:

import fetch from 'node-fetch'
import FormData from 'form-data'
import fs from 'node:fs'
import path from 'node:path'

async function upload(filePath: string) {
const formData = new FormData()
const fileStream = fs.createReadStream(filePath)

formData.append('file', fileStream)
formData.append('lookup_key', '<YOUR-LOOKUP-KEY>') // Optional
const response = await fetch('http://api.zigned.se/rest/v3/files', {
method: 'POST',
headers: {
Authorization: `Bearer <YOUR-ACCESS-TOKEN>`,
},
body: formData,
})

const result = await response.json()
console.log(result)
}

// Replace with the path to your file and your authentication token
const filePath = path.join(__dirname, 'your-file.pdf')

uploadFileUsingNodeFetch(filePath)

How It Works

  • Create a Form with the File: We use form-data to create a form and append our file to it.
  • Read the File: The file is read from the file system using fs.createReadStream.
  • Send the Request: We use node-fetch to send a POST request with the form data to the specified endpoint.
  • Handle the Response: The response is processed and logged to the console.

Remember to replace 'your-file.pdf' with the path to your actual file.


Important: Error Handling and Logging

This is a simplified example. Ensure you include robust error handling and logging. This not only helps in diagnosing issues during file upload but also ensures better stability and reliability of your application.


Next Steps

After uploading your file, you can use the returned file ID in subsequent API calls to reference the uploaded file. This makes managing and using files in your application seamless and efficient.