React&Node(Multer):图像存在于该路径上时未按路径找到

React & Node (Multer): Image is not found by path while it exists on that path

你好,我的网站上有图片上传功能,它是用 NodeJS (Express) 和 Multer 上传到特殊文件夹中的,但问题是当用户上传该图片时,他会被重定向到新创建的路由,并且在那条路线上应该显示图像,但它甚至认为它不存在 这是多个代码:

const imgStorageBaseURL = '/images'
const imgStoragePath = path.join(__dirname, '..', 'images');
const storage = multer.diskStorage({
  destination: (req, file, callback) => {
    const userPath = path.join(imgStoragePath, req.userId);
    fs.mkdir(
      userPath,
      () => callback(null, userPath)
    )
  },


  filename: (req, file, callback) => {
    const filenameParts = file.originalname.split('.');
    const ext = filenameParts.pop();
    const basename = filenameParts.join('.');
    const additionalPath = Date.now() + '' +  Math.floor(Math.random() * (2000 - 500)) + 500;
    callback(null, basename + '-' + additionalPath + '.' + ext);
  }
})

这里是图像链接的数组(将链接保存到数据库中)

 var imgarray = []
 req.files.forEach((file) => {
    imgarray.push(imgStorageBaseURL + '/' + req.userId + '/' + file.filename)
    console.log(imgarray)
})

和反应代码

     {this.state.imageURLs.map((src, k)=>{
         return (
             <img src={src} key={k} alt="Hey" className="img"/>
         )
     })}

检查元素中有源

这是图像存在于该路径上的证据

但是当我在源代码中访问 url 时,我得到了这个

造成这种误解的原因是什么?

谢谢!

虽然图像存在于文件系统中,但未正确放置 "relative" 到 Web 服务器,即您的 React 应用程序。

通常图像放置在为静态指定的单独区域中 files.If 您曾使用 create-react-app 构建您的应用程序,可以从 'public' 文件夹

访问它们
render() {
  // Note: this is an escape hatch and should be used sparingly!
  // Normally we recommend using `import` for getting asset URLs
  // as described in “Adding Images and Fonts” above this section.
  return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
}

这里是 link to the official docs.

具体来说,您应该将您的反应代码更新为:

 {this.state.imageURLs.map((src, k)=>{
     return (
         <img src={process.env.PUBLIC_URL +src} key={k} alt="Hey" className="img"/>
     )
 })}

只需确保移动图像或更新图像保存路径从 multer/express 到 public 文件夹。