【问题标题】:Display image at client side (react) from mongoDB (that has a path to a folder that stores the images at server side)在客户端显示图像(反应)来自 mongoDB(具有存储服务器端图像的文件夹的路径)
【发布时间】:2021-11-17 20:46:51
【问题描述】:

我已经阅读了所有答案,但仍然无法理解问题所在。 我试图在反应时显示来自 MongoDB 的图像,我可以显示路径但不能使用它。 本地主机在 8080 端口上运行。

db 对象如下所示:

{"_id":{"$oid":"614cb6cb8b4b8b3bb8ac7342"},"fileName":"black-sandals-shoes.jpg","filePath":"addedItems\\2021-09-23T17-18-03.302Z-black-sandals-shoes.jpg","fileType":"image/jpeg","fileSize":"104.69-KB","type":"shoes","productType":"shoes","createdAt":{"$date":"2021-09-23T17:18:03.313Z"},"updatedAt":{"$date":"2021-09-23T17:18:03.313Z"},"__v":0}

在 server.mjs 中(addItems 是服务器端存储图片的文件夹)

app.use('/api/addedItems', express.static(path.join(__dirname, 'addedItems'))); 

物品组件:

export default function Item({ id, filePath, type, productType }) {
  return (
    <div className="item">
      {`http://localhost:8080/${filePath}`}
      <img
        src={`http://locallhost:8080${filePath}`}
        className="item-image"
        alt="item-img"
      />
      {/*<span>{type}</span>*/}
      <span>{productType}</span>
      <button>Delete from closet</button>
    </div>
  );
}

这就是我得到的:

http://locallhost:8080/addedItems\2021-09-23T17-18-03.302Z-black-sandals-shoes.jpgitem-img
shoes
Delete from closet

如果可以的话请帮帮我:))

【问题讨论】:

    标签: reactjs mongodb express server path


    【解决方案1】:

    我可以在这里看到一个错字:&lt;img src={`http://locallhost:8080${filePath}`} className="item-image" alt="item-img"/&gt; 将其更改为 localhost,并带有一个“l”。此外,请确保在服务器端保存图像的文件夹是公开的。我在这里找到了一个类似的话题:Load local images in React.js

    编辑您的评论: 这是我在 multer 文档中找到的用于磁盘存储文件上传的确切代码。

    const storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, '/tmp/my-uploads')
      },
      filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null, file.fieldname + '-' + uniqueSuffix)
      }
    })
    
    const upload = multer({ storage: storage })
    

    我强烈建议您接受此操作并进行所需的任何更改。还要确保路径正确,并且底部有上传变量。

    【讨论】:

    • 好的,谢谢。但是现在我已将文件夹位置更改为公共,我必须更改“multer”的路径,当我更改路径时 - 它根本停止上传... const storage = multer.diskStorage({ destination: (req,文件, cb) => { cb(null, '../../react-app/public/addedItems'); }, 文件名: (req, file, cb) => { cb(null, new Date() .toISOString().replace(/:/g, '-') + '-' + file.originalname); } });有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多