返回

如何在 React 中显示公共目录中的图像?

mysql

如何在 React 前端显示存储在公共目录中的图像

问题

在 React 前端显示存储在公共目录中的图像时,可能会遇到以下问题:

  • 获取上传图像名称 :如何从后端获取上传图像的名称?
  • 获取确切的时间戳 :如何获取图像上传时的确切 Date.now() 时间戳?

解决方案

获取上传图像名称

  1. 在后端处理图像上传请求时,将图像名称存储到数据库中。
  2. 通过数据库查询获取图像名称。

获取确切的时间戳

在后端图像上传处理程序中,使用 Date.now() 获取确切的时间戳。

React 前端代码

  1. 使用 useEffect 钩子从数据库中获取图像名称。
  2. 使用 map 函数在前端显示图像。

示例代码

后端 Node.js

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    return cb(null, "./public/images");
  },
  filename: function (req, file, cb) {
    const filename = `${Date.now()}_${file.originalname}`;
    return cb(null, filename);
  },
});

const upload = multer({ storage });

// ...

app.post("/upload", upload.single("image"), async (req, res) => {
  // ...

  // Store the image filename in the database
  await db.query("INSERT INTO images (filename) VALUES (?)", [req.file.filename]);

  // ...
});

React 前端

import { useEffect, useState } from "react";

const ImageDisplay = () => {
  const [images, setImages] = useState([]);

  useEffect(() => {
    // Fetch image names from the database
    fetch("/api/images")
      .then(res => res.json())
      .then(data => setImages(data.images))
      .catch(err => console.error(err));
  }, []);

  return (
    <div>
      {images.map(image => (
        <img src={`/public/images/${image.filename}`} alt={image.filename} />
      ))}
    </div>
  );
};

export default ImageDisplay;

常见问题解答

  1. 如何处理大型图像?
    考虑使用图像压缩或分块上传等技术。

  2. 如何优化图像加载性能?
    使用缓存、懒加载和图像优化技术。

  3. 如何限制用户上传文件的大小和类型?
    使用 Multer 或其他中间件配置上传限制。

  4. 如何在 React 中显示动态生成的图像名称?
    使用 stateuseEffect 钩子管理图像名称,并在图像加载时更新。

  5. 如何防止图像热链接?
    通过使用 Referrer Policy 或 CORS 限制对图像的外部访问。