Formidable Files 上传命名文件问题

Formidable Files uploads naming files issue

提问人:geniar99s 提问时间:11/14/2023 最后编辑:enzogeniar99s 更新时间:11/14/2023 访问量:26

问:

我正在尝试使用强大的后端从下一个 js 应用程序 (T3Stack) 上传文件,以在一个名为 upload 的文件中上传多个文件,它实际上正在上传,但我有 2 个问题,我想将该文件上传到上传文件夹中,但我正在发送电子邮件(电子邮件只是我想要创建的文件夹名称)我想检查是否创建了该电子邮件文件夹,然后继续在其中上传这些文件该文件夹具有文件的原始名称,但遗憾的是 Formidable 正在创建一个我无法更改的新名称,这里是前端代码:

 const handleFileUpload = async (fileInput) => {
const files = fileInput.target.files;

const formData = new FormData();
for (let i = 0; i < files.length; i++) {
  formData.append("multiple-files", files[i]);
}
formData.append("email", user.email);

try {
  const res = await fetch("http://localhost:3000/api/files", {body: formData})

  if (res.status === 200) {
    toast.success("Success");
  } else {
    toast.error("Failed");
  }
} catch (error) {
  console.error("Error uploading files:", error);
  toast.error("Failed to upload files");
}
};

这是后端代码:

import { NextApiHandler } from "next";
import formidable from "formidable";
import path from "path";
import { promises as fs } from "fs";

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

const readFile = (req: any): Promise<{ fields: formidable.Fields; files: formidable.Files }> => {
  const options: formidable.Options = {};
  options.uploadDir = path.join(process.cwd(), "/uploads");
  options.maxFileSize = 1024 * 1024; // 1 MB

  return new Promise((resolve, reject) => {
    const form = formidable(options);

    form.parse(req, (err, fields, files) => {
      if (err) {
        reject(err);
        return;
      }
      resolve({ fields, files });
    });
  });
};


const handler: NextApiHandler = async (req, res) => {
  if(req.method === "POST"){
  try {

    // Create the 'uploads' folder if it doesn't exist
    await fs.mkdir(path.join(process.cwd(), "/uploads"), { recursive: true });
    // // Read files from the request
    const { fields, files } = await readFile(req);
    
    // Assuming you are handling multiple files, adjust accordingly if needed
    const fileDataArray = (files.image || []).map((file) => ({
      name: file.originalFilename, // Use the original filename
      size: file.size,
      path: `/uploads/${fields.email}/${file.newFilename}`,
      extension: file.extension,
    }));

    res.status(200).json({
      error: false,
      data: fileDataArray.map((fileData) => ({
        name: fileData.name,
        path: fileData.path,
      })),
    });
  } catch (error) {
    console.error("Error processing file upload:", error);
    res.status(500).json({ error: true, message: "Internal Server Error" });
  }
}
};

export default handler;
JavaScript 下一个 .js 文件上传 强大

评论


答: 暂无答案