【问题标题】:why is this not rendering my image? Even when the src is correct为什么这不渲染我的图像?即使 src 是正确的
【发布时间】:2021-08-23 11:30:42
【问题描述】:

我正在尝试使用 multer 和 React 构建一个图像上传器,我已经正确地完成了这个,因为图像正确地上传到了数据库。问题是当我尝试在 src 中渲染图像时。正如您在此处看到的,我尝试通过设置以下代码来渲染图像:

我已将图像的文件夹 trainfitbackend/uploads/name 设置为我存储图像但它们未呈现的位置。

{`../trainfitbackend/uploads/${client.image}`}

这里是完整的代码:

import React, {useState, useEffect} from 'react'
import axios from 'axios'
import {
    BrowserRouter as Router,
    Switch,
    Route,
    Link
  } from "react-router-dom";
import ClientForm from './clientform.js'

function Clients() {

    const [data, setData] = useState([])

    useEffect(() => {
        axios.get('http://localhost:4000/clients')
        .then(res => setData(res.data))
    }, [])
    console.log(data)
    return (
        <div>
            <Link to="/addClient"><button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">New Client</button></Link>
            <div class="min-h-screen bg-gray-100 flex flex-row">
            <div class="container flex flex-row">
        {data.map((client) => {
                return (
                      <div class="max-w-sm py-32">
                        <div class="bg-white relative shadow-lg hover:shadow-xl transition duration-500 rounded-lg">
                          <img class="rounded-t-lg" src={`../trainfitbackend/uploads/${client.image}`} alt="" /> 
                          <div class="py-6 px-8 rounded-lg bg-white">
                            <h1 class="text-gray-700 font-bold text-2xl mb-3 hover:text-gray-900 hover:cursor-pointer">{client.firstName}</h1>
                            <p class="text-gray-700 tracking-wide">{client.lastName}</p>
                            <Link to={`Clients/${client._id}`}><button class="mt-6 py-2 px-4 bg-yellow-400 text-gray-800 font-bold rounded-lg shadow-md hover:shadow-lg transition duration-300">See more details</button></Link>
                          </div>
                        </div>
                      </div>  
                )
            })}
               </div>   
              </div>
        </div>
    )
}

export default Clients

【问题讨论】:

  • 你在 DevTools 的浏览器中看到的图片的 src 是什么?可能它有 http 协议而不是 file 本地图像的协议
  • 是的,它没有文件协议,怎么解决?
  • 如果您打算将文件存储在本地计算机上,则必须在 src 字符串中使用文件协议
  • 如何使用文件协议?
  • 您是否将文件存储在 BE 端?

标签: reactjs multer


【解决方案1】:

在聊天How to fetch images from node.js server's folder in URL?的讨论中解决了

图片已移至公用文件夹

【讨论】:

    猜你喜欢
    • 2016-04-09
    • 2014-01-23
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    相关资源
    最近更新 更多