Skip to content

Upload document - Nodejs

You can upload a document - Nodejs by creating a FormData object and add a file field to that object. The resulting form can be posted to the /v1/files endpoint.

ts

const form = new FormData();
const buffer = fs.readFileSync("./classic-form-all-field-types.pdf");
const filename = "classic-form-all-field-types.pdf";

const blob = new Blob([buffer], { type: "application/pdf" });
form.append("file", blob, filename);

const path = "/v1/files";
const url = `${api_url}${path}`;
const method = "POST";
const headers = getAuthorizationHeaders(method, path);

const response = await fetch(url, {
  headers,
  method,
  body: form,
});

Code

ts
import dotenv from "dotenv";
dotenv.config();

import * as fs from "node:fs";
import { getError } from "./errorhandling";
import { getAuthorizationHeaders } from "./authorization";

const api_url = process.env.UNOPDF_API_URL;

async function postDocument() {
  // #region upload_file

  const form = new FormData();
  const buffer = fs.readFileSync("./classic-form-all-field-types.pdf");
  const filename = "classic-form-all-field-types.pdf";

  const blob = new Blob([buffer], { type: "application/pdf" });
  form.append("file", blob, filename);

  const path = "/v1/files";
  const url = `${api_url}${path}`;
  const method = "POST";
  const headers = getAuthorizationHeaders(method, path);

  const response = await fetch(url, {
    headers,
    method,
    body: form,
  });
  // #endregion upload_file
  
  if (response.status !== 200) {
    const error = await getError(response);

    console.error(error);
    throw new Error(`Error "${error}" calling UnoPdf API "${method} ${url}".`);
  }

  return await response.json();
}

postDocument().then((doc) => console.log(doc));

Running the example

  • Download the rest - Upload document - Nodejs project
  • Unzip the file to a directory rest-upload-document-nodejs.
    shell
    unzip rest-upload-document-nodejs.zip -d rest-upload-document-nodejs
  • Open a terminal and go to that directory
    shell
    cd rest-upload-document-nodejs
  • Install dependencies
    shell
    npm install
    shell
    yarn
  • Start the project
    shell
    npm run start
    shell
    yarn start