Next.js 上传多张图片

问题描述 投票:0回答:1

我想上传多个图像并从响应中获取路径,但我有一些问题。 上传的图像的名称示例: basic.png 和 starter.png 当我上传它们时,它们会保存在服务器上,名称为: basic.png 和 basic.png.starter.png 以及每个下一个文件名: basic.png.starter.png ..png 而不是: basic.png 和 starter.png。我在响应数据方面遇到的第二个问题,我希望 res.data 是所有上传图像路径示例的数组或对象: data: ['path1', 'path2'] 而我的响应只有第二个文件路径,看起来像: path 我该如何修复这个问题?

主文件:

async function uploadImages(ev) {
    const files = ev.target?.files;
    if (files?.length > 0) {
      const data = new FormData();
      for (const file of files) {
        data.append("file", file);
        console.log(data);
      }
      const res = await axios.post("/api/upload", data);
      console.log(res.data);
    }
  }

api/上传文件:

import { createRouter } from "next-connect";
import multer from "multer";

const nextConnect = createRouter();

let filename = new Date().toISOString().replace(/:/g, '-') + "-";

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "./images");
  },
  filename: (req, file, cb) => cb(null, getFileName(file)),
});

const upload = multer({ storage: storage });

const getFileName = (file) => {
  filename += file.originalname;
  return filename;
};

nextConnect.use(upload.array("file"));

nextConnect.post((req, res) => {
  res.status(200).json({ data: `/images/${filename}` });
});

export default nextConnect.handler({
  onError(error, req, res) {
    res
      .status(501)
      .json({ error: `Sorry something Happened! ${error.message}` });
  },
  onNoMatch(req, res) {
    res.status(405).json({ error: `Method '${req.method}' Not Allowed` });
  },
});

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

我尝试更改 getFileName 函数,但结果更糟。我在想如何更改 res.data,但我不知道该怎么做。

next.js upload multer
1个回答
0
投票

我找到了解决方案,对于每个遇到同样问题的人来说,这就是解决方案:

第一个问题:

您需要删除

let filename = new Date().toISOString().replace(/:/g, '-') + "-";

const getFileName = (file) => {
  filename += file.originalname;
  return filename;
};

并改变

filename: (req, file, cb) => cb(null, getFileName(file)),

filename: (req, file, cb) => {
    const newFilename =
      new Date().toISOString().replace(/:/g, "-") + "-" + file.originalname;
    cb(null, newFilename);
  },

第二个问题:

您需要添加

let filenames = [];

并且在

  filename: (req, file, cb) => {
    const newFilename =
      new Date().toISOString().replace(/:/g, "-") + "-" + file.originalname;
    cb(null, newFilename);
  },

添加

filenames.push(newFilename);

之前

    cb(null, newFilename);
And change
nextConnect.post((req, res) => {
  res.status(200).json({ data: `/images/${filename}` });
});

nextConnect.post((req, res) => {
    const paths = filenames.map(filename => `/images/${filename}`);
    res.status(200).json({ path: paths });
  });
© www.soinside.com 2019 - 2024. All rights reserved.