Next JS, отправка файлов на сервер с указанием пути сохранения

Как мне передать в теле запроса пути для сохранения загруженных файлов и получить путь их сохранения

код отправки файлов

import { useState, useRef } from "react";

export default function Admin() {
  const [isLoading, setIsLoading] = useState(false);
  const inputFileRef = useRef<HTMLInputElement | null>(null);
  const inputTextRef = useRef<HTMLInputElement | null>(null);

  const foto = "foto";

  const handleOnClick = async (e: React.MouseEvent<HTMLInputElement>) => {
    e.preventDefault();

    if (!inputFileRef.current?.files?.length) {
      alert("Выберите изображения для загрузки");
      return;
    }
    Object.values(inputFileRef.current.files).forEach((file) => {
      console.log("public" + "/" + foto + "/" + file.name);
    });
    setIsLoading(true);

    const formData = new FormData();
    Object.values(inputFileRef.current.files).forEach((file) => {
      formData.append("file", file);
    });
    formData.append("text", foto);

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

    const body = (await response.json()) as {
      status: "ok" | "fail";
      message: string;
    };

    // alert(body.message);

    if (body.status === "ok") {
      inputFileRef.current.value = "";
      // Do some stuff on successfully upload
    } else {
      // Do some stuff on error
    }

    setIsLoading(false);
  };

  return (
    <form>
      <div>
        <input type="text" name="text" ref={inputTextRef} defaultValue="foto" />
        <input type="file" name="myfile" ref={inputFileRef} multiple />
      </div>
      <div>
        <input
          type="submit"
          value="Upload"
          disabled={isLoading}
          onClick={handleOnClick}
        />
        {isLoading && ` Подождите...`}
      </div>
    </form>
  );
}

код API сервера

import { NextApiHandler, NextApiRequest } from "next";
import formidable from "formidable";
import path from "path";
import fs from "fs/promises";

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

const readFile = (
  req: NextApiRequest,
  saveLocally?: boolean
): Promise<{
  fields: formidable.Fields;
  files: formidable.Files;
}> => {
  const options: formidable.Options = {};
  if (saveLocally) {
    options.uploadDir = path.join(process.cwd(), "/public/img");
    options.filename = (name, ext, path, form): any => {
      return path.originalFilename;
    };
  }
  // options.maxFileSize = 4000 * 1024 * 1024;
  const form = formidable(options);
  return new Promise((resolve, reject) => {
    form.parse(req, (err, fields, files) => {
      // let text = fields.text?.join(" ")!;
      if (err) reject(err);
      resolve({ fields: {}, files: {} });
    });
  });
};

const handler: NextApiHandler = async (req, res) => {
  try {
    await fs.readdir(path.join(process.cwd() + "/public", "/img"));
  } catch (error) {
    await fs.mkdir(path.join(process.cwd() + "/public", "/img"));
  }
  await readFile(req, true);
  res.json({ done: "ok" });
};

export default handler;

Ответы (0 шт):