NodeJS path参数必须是字符串类型,或者是Buffer或URL的示例,使用强大的

eh57zj3b  于 2023-04-05  发布在  Node.js
关注(0)|答案(1)|浏览(144)

我试图上传文件到aws s3使用强大的。它的工作罚款为单个文件,但当我去与多个文件显示错误的“路径”参数必须是类型字符串或缓冲区或URL的示例。收到未定义的“在 Postman

exports.addProduct = asyncHandler(async (req, res) => {
  const form = formidable({
    multiples: true,
    keepExtensions: true,
  });

  form.parse(req, async function (err, fields, files) {
    try {
      if (err) {
        throw new CustomError(err.message || "Something went wrong", 500);
      }

      let productId = new Mongoose.Types.ObjectId().toHexString();
    
      // check for fields
      if (
        !fields.name ||
        !fields.price ||
        !fields.description ||
        !fields.collectionId
      ) {
        throw new CustomError("Please fill all details", 500);
      }

      // handling images
      let imgArrayResp = Promise.all(
        Object.keys(files).map(async (filekey, index) => {
          const element = files[filekey];

          console.log(`line 50 ${element.filepath} `)
          console.log(typeof(element))
        
          const data = fs.readFileSync(element.filepath);

          console.log("line 62", data);

        //   console.log(typeof(s3FileUpload))
          const upload = await s3FileUpload({
            bucketName: config.S3_BUCKET_NAME,
            key: `products/${productId}/photo_${index + 1}.png`,
            body: data,
            contentType: element.mimetype,
          });
          return {
            secure_url: upload.Location,
          };
        })
      );

      let imgArray = await imgArrayResp;

      const product = await Product.create({
        _id: productId,
        photos: imgArray,
        ...fields,
      });

      if (!product) {
        throw new CustomError("Product was not created", 400);
        //remove image
      }
      res.status(200).json({
        success: true,
        product,
      });
    } catch (error) {
      return res.status(500).json({
        success: false,
        message: error.message || "Something went wrong",
      });
    }
  });
});
let imgArrayResp = Promise.all(
        Object.keys(files).map(async (filekey, index) => {
          const element = files[filekey];

          console.log(`line 50 ${element.filepath} `)
          console.log(typeof(element))
        
          const data = fs.readFileSync(element.filepath);

          console.log("line 62", data);

        //   console.log(typeof(s3FileUpload))
          const upload = await s3FileUpload({
            bucketName: config.S3_BUCKET_NAME,
            key: `products/${productId}/photo_${index + 1}.png`,
            body: data,
            contentType: element.mimetype,
          });
          return {
            secure_url: upload.Location,
          };
        })
      );

我试图cosole元素的类型它在对象。我认为元素。filepath是不可访问的

r3i60tvu

r3i60tvu1#

const element = files[filekey][0];

也许元素是数组

相关问题