【问题标题】:Image not rendering in my Admin application图像未在我的管理应用程序中呈现
【发布时间】:2022-01-26 15:01:12
【问题描述】:

我正在创建一个管理应用程序,我想在其中显示存储在数据库中的上传产品图像。我已在 MongoDB 中将图像作为对象 ID 上传。但是管理应用程序中的图像容器显示存储在数据库中的图像数量。但图像不显示。我也尝试过使用绝对 URL,但这也不起作用。

这是我上传图片的代码:

{productPictures.length > 0
          ? productPictures.map((pic, index) => (
              <div key={index}>{pic.name}</div>
            ))
          : null}
        <input
          type="file"
          name="productPictures"
          onChange={handleProductPictures}
        />

这是显示图像的代码:

<label className="key">Product Pictures</label>
            <div style={{ display: "flex" }}>
              {productDetails.productPictures.map((picture) => (
                <div className="productImgContainer">
                  <img src={generatePublicUrl(picture.img)} alt="" />
                </div>
              ))}
            </div>

生成 URL 函数如下所示:

const api ='http://localhost:2000/'
// const api = 'http://192.168.0.104:2000/'
const generatePublicUrl = (fileName) => {
    return `http://localhost:2000/src/uploads/products/${fileName}`;
}
export {
    api,
    generatePublicUrl
};

将产品保存在数据库中的功能:

const createProduct= (req, res) => {
  const { name, price, description, category, quantity, createdBy } = req.body;
  let productPictures = [];

  if (req.files.length > 0) {
    productPictures = req.files.map((file) => {
      return { img: file.location };
    });
  }

  const product = new Product({
    name: name,
    slug: slugify(name),
    price,
    quantity,
    description,
    productPictures,
    category,
    createdBy: req.user._id,
  });

  product.save((error, product) => {
    if (error) return res.status(400).json({ error });
    if (product) {
      res.status(201).json({ product, files: req.files });
    }
  });
        
}

程序中上传的图片如下所示: Open image here

但是页面显示空白区域并且文件名在检查时显示未定义。 Open image here

【问题讨论】:

  • 你能分享一个productDetails.productPictures的例子吗
  • 我会从一开始就开始调试这个。那么req.files 中的每个文件是否都具有位置属性,它是您所期望的吗?您使用什么库进行上传?
  • @Molda 我正在使用 Multer 库上传文件。 req.files 有 src/uploads/products 作为位置属性。我已将图像保存在该目录中,但未获取和渲染图像。
  • @Mohammednaji 你的意思是你想要那些上传的图片名称?
  • @niteshraj 所以你是说 productPictures 对象在你保存到数据库之前看起来像这样[{ img: 'src/uploads/products' }, ...] ??那么你在哪里相同的文件名(xxx.jpeg)?根据文档(您应该阅读过),该文件有这些道具filename/destination/path/etc.,但您决定使用location,文档中甚至没有提到,为什么? Documentation

标签: javascript html node.js reactjs


【解决方案1】:

我相信您正在尝试将non-public path 添加到源中。 您需要将文件添加到public 文件夹,这样您就可以使用路径调用资产,否则您可以导入images,然后将它们添加到src 属性中

编辑 1:

return `http://localhost:2000/src/uploads/products/${fileName}`;

这不起作用,您无法访问 src 中的内容 您可以访问的唯一文件夹是public 文件夹

【讨论】:

    猜你喜欢
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    相关资源
    最近更新 更多