File Uploads

You thought handling post data and zero-config api routes are awesome? How about easy-peasy file uploads?

#
handle » upload

To enable file uploads, we'll accompany the post handler with an upload handler. Together, they'll be responsible for handling multipart form submissions.

import fs from 'fs';
import { handle, json } from 'next-runtime';

export const getServerSideProps = handle({
  async upload({ file, stream }) {
    stream.pipe(fs.createWriteStream(`/uploads/${file.name}`));
  },

  async post({ req: { body } }) {
    return json({ message: 'Thanks, file accepted!' });
  },
});

The upload handler gets a file object containing name, type and size properties, as well as a readable stream. Either use the stream to write the file to your file system, or pipe it to an object store like S3.

If you wish to store the file locally, you might also simply specify the uploadDir instead, and let next-runtime handle the writing for you. More about that, on the api pages.

Possibly unnecessary, but here's a form that could be submitting data to this handler:

export default function MyPage({ name, message }) {
  if (message) {
    return <p>{message}</p>;
  }

  return (
    <form method="post" encType="multipart/form-data">
      <input name="file" type="file" />
      <button type="submit">submit</button>
    </form>
  );
}

Don't forget to specify encType="multipart/form-data" when adding file inputs.

Just as with the standard post handler, this form can be upgraded to a Form as well. Please see data updates - upgrading to form for how to do that.