user12858805
user12858805

Reputation: 21

How to upload a file with NextJS and formidable?

I am trying to utilize formidable to access a file and eventually post it to a file storage system by following this post: Create upload files api in next.js. I am logging the data, but am getting confused about the output. When I try and access data.files.resume.filepath I get undefined.

The data looks like:

{ fields: {}, files: { resume: [ [PersistentFile] ] } }

And when I log data.files.resume I get this which shows the filepath:

[
  PersistentFile {
    _events: [Object: null prototype] { error: [Function (anonymous)] },
    _eventsCount: 1,
    _maxListeners: undefined,
    lastModifiedDate: 2023-02-09T01:59:50.924Z,
    filepath: 'C:\\Users\\Me\\AppData\\Local\\Temp\\21eef37a9191459ae49bb110f',
    newFilename: '21eef37a9191459ae49bb110f',
    originalFilename: 'thankyou.pdf',
    mimetype: 'application/pdf',
    hashAlgorithm: false,
    size: 57285,
    _writeStream: WriteStream {
      fd: null,
      path: 'C:\\Users\\Me\\AppData\\Local\\Temp\\21eef37a9191459ae49bb110f',
      flags: 'w',
      mode: 438,
      start: undefined,
      pos: undefined,
      bytesWritten: 57285,
      closed: false,
      _writableState: [WritableState],
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,
      [Symbol(kFs)]: [Object],
      [Symbol(kIsPerformingIO)]: false,
      [Symbol(kCapture)]: false
    },
    hash: null,
    [Symbol(kCapture)]: false
  }
]

and when I log the data.files.resume.filepath I get undefined

Front End Form Submit:

const formData = new FormData();
formData.append("resume", resume);

const response = await fetch("/api/apply", {
    method: "POST",
    body: formData,
});

NextJS API:

import type { NextApiRequest, NextApiResponse } from "next";
import { IncomingForm } from "formidable";

export const config = {
  api: {
    bodyParser: false,
  },
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== "POST") {
    return;
  }

  // parse form with a Promise wrapper
  const data = await new Promise((resolve, reject) => {
    const form = new IncomingForm();
    form.parse(req, (err, fields, files) => {
      if (err) return reject(err);
      resolve({ fields, files });
    });
  });

  console.log("------");
  console.log(data);
  console.log("------");
  console.log(data.files.resume);
  console.log("------");
  console.log(data.files.resume.filepath); // this logs undefined

  res.status(200).json(data);
}

I followed this StackOverflow article: Create upload files api in next.js and have tried logging each step, but still get undefined for the filepath. Any help or guidance is greatly appreciated!

Upvotes: 2

Views: 5466

Answers (2)

Jahangeer i
Jahangeer i

Reputation: 1

You have to use data.files.resume[0]. Because resume is an object inside that resume, you have persistence at index '0'. At persistence, you have the file name, path, original name, etc. Using the data, you can get your file.

I was just looking for that, so I decided to implement it in Express JS to know what exactly happens here, so in my NextJS project I have invested my knowledge.

Upvotes: -1

Walle Cyril
Walle Cyril

Reputation: 3247

data.files.resume is an array

use data.files.resume[0].filepath instead or use first values helper

import { firstValues } from 'formidable/src/helpers/firstValues.js';

Upvotes: 1

Related Questions