【问题标题】:Display an image from multer and a database of type uploads / files.jpg显示来自 multer 的图像和类型为 uploads / files.jpg 的数据库
【发布时间】:2021-07-28 19:54:18
【问题描述】:

我刚刚使用 NodeJS 在 Back 中配置了 Multer,一切正常。我可以将图像保存在我的数据库“uploads/img.jpg”中,并且该图像也显示在 Back 中名为“uploads”的文件夹中。

现在我正在尝试使用 ReactJS 和 map 方法显示图像,但我遇到了困难:由于“上传/”,我无法显示图像。这是我的代码:

const Users = () => {
  const [users, setUsers] = useState([]);
  const classes = useStyles();

  useEffect(() => {
    const getUserss = async () => {
      const result = await axios.get("/users");
      setUsers(result.data);
    };
    getusers();
  }, []);

const tableHeader = columns.map((column) => (
    <TableCell key={column.id} align={column.align} style={{ minWidth: column.minWidth }} >
      {column.label}
    </TableCell>
  ));

  const mainContent = users
    .map((user) => {
      console.log(user);
      return (
        <TableRow hover role="checkbox" tabIndex={-1} key={customer.code}>
          <TableCell align="center" className={classes.test}>
            <Avatar className={classes.avatar} src= {?} /> {/* My problem is here */}
          </TableCell>
          <TableCell align="center">{user.name}</TableCell>
          <TableCell align="center">{user.details}</TableCell>
        </TableRow>
      );
    });

 return (
      <TableContainer className={classes.container}>
        <Table stickyHeader aria-label="sticky table">
          <TableHead>
            <TableRow>{tableHeader}</TableRow>
          </TableHead>
            <TableBody>{mainContent}</TableBody>
        </Table>
      </TableContainer>
 );
};

export default Users;

以及我的 console.log(user) 的结果:

我还在 NodeJS 中使用 MVC 模型配置了两个文件,但我不知道这是否可以帮助我使用 map 方法。控制器中的拳头:

class Images {
    static sendImg = (req, res) => {
        const { rep, img } = req.params;
        res.sendFile(`uploads/${img}`, { root: "./" });
      };
}

module.exports = Images;

还有第二条路线:

const imgCtrl = require("../controllers/images");
const images = require("express").Router();

images.get("/:img", imgCtrl.sendImg);

module.exports = images;

我在路线中也有一个索引:

const images = require('./images');

module.exports = (app) => {
  app.use('/uploads', images);
};

【问题讨论】:

    标签: node.js reactjs image multer


    【解决方案1】:

    我终于找到了我的问题的答案。代码如下:

    src={`http://xxx/${user.path}`}
    

    【讨论】:

      【解决方案2】:

      尝试添加这个:

      app.use('/uploads', express.static(path.join(__dirname, 'relative_path_to_uploads_folder')));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-19
        • 2018-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-24
        • 2016-11-23
        • 1970-01-01
        相关资源
        最近更新 更多