Server Functions and Documents

Is it viable to utilize server actions for file uploads in a Next.js project, such as storing images, documents, spreadsheets, and PDFs in the public folder?

While Node.js offers options like Multer and Formidable for this purpose, I am faced with challenges using server actions due to its lack of support for

'Content-Type': 'multipart/form-data'

I aim to store applicant details including name, email, phone number, and resume. Can server actions facilitate this process?

"use server";
import prisma from "@/utils/prisma";
import fs from "fs";
import FormData from "form-data";
import path from "path";
import { v4 as uuid } from "uuid";

const uploadApplicant = async (
  name: string,
  email: string,
  tel: string,
  file: File | null
) => {
  const fileName = uuid();
  const formData = new FormData();

  formData.append("file", file);
  console.log("Form data: ", formData);
  const binaryData = formData.getBuffer();

  console.log("Binary: ");
  console.log(binaryData);

  const filePath = path.join(
    __dirname,
    "../../../../",
    "public",
    "uploads",
    `${fileName}.pdf`
  );

  fs.writeFileSync(filePath, binaryData, "binary");

  await prisma.applicant.create({
    data: {
      name,
      tel,
      email,
      fileName,
    },
  });
};

export default uploadApplicant;

Answer №1

To extract the File object from the binary data in the FormData instance that is sent to the server, follow these steps:

'use strict';

import { writeFile } from 'fs/promises';
import { join } from 'path';

export async function handleUpload(formData: FormData) {
  const file = formData.get('file');

  if (!file) throw new Error('No file was uploaded');

  const arrayBuffer = await file.arrayBuffer();
  const buffer = Buffer.from(arrayBuffer);

  const filePath = join(process.cwd(), file.name);
  await writeFile(filePath, buffer);

  console.log(`Please check ${filePath} to view the uploaded file`);

  return { uploadSuccess: true };
}

Answer №2

In the realm of web development, File objects are specifically designed for use in the browser environment and are not compatible with Node.js.

When transferring files to a server, the complete File object is typically not sent over. Instead, the file data is transmitted as a binary stream (array buffer). This process is commonly facilitated by utilizing a FormData object for handling file uploads or through client-side management of file transfers.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using both withNextIntl and withPlaiceholder simultaneously in a NextJS project causes compatibility issues

I recently upgraded to NextJS 14 and encountered an issue when deploying my project on Vercel. The next.config.mjs file in which I wrapped my nextConfig in two plugins seemed to prevent the build from completing successfully. As a workaround, I decided t ...

Unable to access attributes of an unknown object (referencing 'Person')

I'm currently facing an issue when trying to POST data from my Next.js project to my MySQL database. Here is my frontend code: import React from 'react' import { useReducer, useEffect, useState } from 'react' import Axios from &ap ...

Error: Requested URLs must be absolute and valid

Encountering an error while using the latest version of openid-client in a next-js application. Unhandled Runtime Error TypeError: only valid absolute URLs can be requested 3 | 4 | const oidcConfig = async () => { > 5 | const issuer = await I ...

Investigating potential causes for the crash of the Next.js Node Server: "npm ERR! code ELIFECYCLE errno 3221225477"

I recently encountered an error on node version 14.16.0, and it happened twice already. The first instance was when I created a react component using the @mui/lab/DateTimePicker. I didn't need to install it since @mui/lab was already present in the pr ...

Avoid the issue of having duplicate user ids by implementing a locked thread feature within Next.js

My database setup involves using MongoDB to store user data, with the user id incrementing each time a new user registers (e.g. 1, 2, 3, 4, etc). To generate the user id, I have the following code snippet. The collection where user data is stored is named ...

Getting an error in NextJs when trying to execute a function in the API folder within pages, it is throwing the error message "'res.status is not

I'm currently working with NextJs and I'm in the process of setting up a subscription form to forward data to MailChimp. However, I've encountered an error that is showing: res.status is not a function This particular file resides within ...

What could be causing a blank page to appear after being redirected? (Using NextJS 13 API Route)

After struggling with this issue for 2 days, I'm throwing in the towel and reaching out to the community for assistance. I've been tasked with setting up a basic login system for a new project using NextJS v13. However, it seems like a lot has c ...

Enhancing NextJS/playwrights with the latest nodejs upgrade?

I am facing issues with my Vercel build due to Playwright's outdated Node.js version: Error: Node.js version 12.x is deprecated. Starting from 2022-08-09, builds will fail unless the Node.js Version is set to 16.x in Project Settings. This change wa ...

Having trouble with Firebase admin in your Next.js/Stripe webhook integration?

I've encountered an issue when using the stripe webhook in Next.js. Every time I attempt to set it up, I receive the following error: unable to detect a project id in this environment I initially tried setting it up in the app router and then trans ...

What is the best way to output a list of objects retrieved from an API? The .map method is not properly retrieving the data

When I attempt to display all companies on my page using the .map method, it throws the following error (TypeError cias.map is not a function): Error Code: import fetch from 'isomorphic-unfetch' import Link from 'next/link' import { C ...

What functionality does the --use-npm flag serve in the create-next-app command?

When starting a new NextJS project using the CLI, there's an option to use --use-npm when running the command npx create-next-app. If you run the command without any arguments (in interactive mode), this choice isn't provided. In the documentati ...

Integrating Octokit middleware in Next.js for enhanced functionality

Currently, I am in the process of honing my skills by creating a GitHub app. In Octokit, there is a feature called createNodeMiddleware that caught my attention. However, integrating it with next.js seems to pose some challenges. My main issue right now re ...

What are the advantages of using global.mongoose for caching the MongoDB connection?

What is the reason for adding global.mongoose to cache the MongoDB connection? import mongoose from 'mongoose' let cached = global.mongoose if (!cached) { cached = global.mongoose = { conn: null, promise: null } } What is the purpose of this ...

Ways to halt the expressjs server

After deploying my express and nextjs based app on EC2, I encountered an issue where the server automatically starts Nginx and node with different process IDs after I attempt to stop it by killing the process. This is happening even without using tools lik ...

Impressive javascript - extract file from formData and forward it

Presented here is my API handler code. // Retrieve data. const form = formidable({ multiples: true }); form.parse(request, async (err: any, fields: any, files: any) => { if (!drupal) { return response.status(500).send('Empty ...

Unlock the full potential of integrating external APIs with Next.js

As a newcomer to NextJs, I am facing the task of making calls to an external Python API from my frontend. Upon discovering NextJs's integrated API feature through creating folders in the app directory, namely api/resource/route, I am wondering what th ...

CLI package enables exporting API facilities

I have a mono repository containing a CLI package (packages/cli) and a web application (apps/web). I want to utilize the public API of the CLI within the web app. The CLI package is packaged with tsup: export default defineConfig({ clean: false, dts: ...

Securing your Next.js App with Express JWT Authentication

After setting up a /api/login endpoint to handle user login functionality, I created a login.js page to send form data to the login API. The login API authenticates user credentials stored in the database, generates a token, and saves it to a cookie. awai ...

Finding the Node.js log location during deployment in Heroku

My Node app on Heroku is giving me trouble. It deploys without any errors, but it crashes right at the start. The log provided below doesn't point to the issue clearly. When I try to access the suggested log at .npm/_logs/2021-04-22T19_59_52_474Z-debu ...

Utilizing Docker for Next.js to leverage multi-core processing

I currently have my Next.js web application (SSG and SSR) deployed on a VPS with 6 CPU cores. The application is containerized using Docker and managed through a Docker Compose stack. It's running behind Traefik as a reverse-proxy. Here's an exa ...