【问题标题】:Display image stored as a Path string in the Database in React在 React 的数据库中显示存储为路径字符串的图像
【发布时间】:2020-05-26 14:53:52
【问题描述】:

我想在 React 中显示位于 src/images 文件夹中的图像。此图像有一个 PATH 存储在数据库中,看起来像这样“../images/profilepic.jpg”。我进行 api 调用,获取 PATH 字符串并将其保存在名为 profilepic 的状态中,到目前为止,这一切正常。然后我将状态变量分配给 profilepic 变量,当我“console.log()”它时正确分配。

问题是当我使用<img src{profilepic} alt="myprofilepic"/> 时,我无法在网站上显示此图像。我已经尝试了过去问题中建议的几乎所有方法,但都没有奏效。我试图将状态this.state.profilepic(分配给它的字符串PATH)作为道具传递给单独的组件,但我仍然遇到同样的问题。使用 <img src=(require{profilepic}) 会产生错误,因为 require 只会使用字符串 URL。

任何人都可以指出一个教程的方向,其中图像作为 URL/路径字符串存储在数据库中,并在 React 中调用和使用。即使它不是一个完整的项目,我也想知道如何从 React 前端完成。如果这不是在 React 中处理动态图像的推荐方法,那么将图像作为 BLOB 存储在数据库中,然后在 React 中调用实际图像本身而不是 PATH 是否更可取?

获取调用:

getUserdetails(){
const userid = this.state.userid;
axios.get(`http://localhost:5000/getuser/details?userid=${userid}`)
.then(json => {
  if(json.data.success){
    this.setState({
        username: json.data.username,
        email: json.data.email,
        fullname: json.data.fullname,
        company: json.data.company,
        profilepic: json.data.propic
    })
    profilepic = this.state.profilepic
    console.log(profilepic)
    this.newprofile(profilepic)
  } 
})}

渲染输出

return (

        <div className="accout-page">
            <div className="sidebar">
            <Images profpic={profilepic} />
                <p><input type="file" onChange={this.onchangeImage} /><button type="button" onClick={this.uploadimage}>Upload</button></p>
    <p>Username: {username}</p>
    <p>Full Name: {fullname}</p>
    <p>Company: {company}</p>
    <p>Email: {email}</p>
            </div>
            <div className="content">
                <h1>Edit your details here</h1>
                <div className="form-error-info">{updateMessage}</div>
                <form>
                <div className="form-group">
                <label>Full Name:</label>
                <input 
                type="text"
                placeholder={fullname}
                onChange={this.onNameChange} required/></div>
                <div className="form-group">
                <label>Company:</label>
                <input
                type="text"
                placeholder={company}
                onChange={this.onCompanyChange} required/></div>
                <div className="form-group">
                <label>Current Password:</label>
                <input
                type="password"
                placeholder="enter current password"
                onChange={this.onoPassChange} required/></div>
                <div className="form-group">
                <label>New Password:</label>
                <input
                type="password"
                placeholder="enter new password"
                onChange={this.onPassChange} required/></div>
                <button className="btn btn-light" type="button" onClick={this.onSubmit}>Update</button>
                </form>
            </div>
        </div>
    )

图像组件:

class Images extends React.Component{

render(){

    const profpic = this.props.profpic;
    console.log(profpic)
return(
    <div>
        <img src={profpic} alt="profile pic" width="100px" height="100px" />
    </div>
)}}

【问题讨论】:

  • 你能从你的代码中添加 sn-ps 吗?那样很难理解。

标签: reactjs


【解决方案1】:

所以,基本上你应该在你的服务器上拥有共享文件夹“images”并在那里存储图像。您必须能够通过

之类的路径打开图像

http://localhost:8080/images/profilepic123.jpg

之后你就可以使用这个代码sn-p了

<img src='/images/profilepic123.jpg' alt="myprofilepic"/>

<img src={profilePic} alt={profileName}/>

【讨论】:

  • 我有点困惑。我需要将此共享图像文件夹放在与我的反应应用程序相同的文件夹中吗?我还在上面看到您输入的端口为 8080,但我为 api 提供服务的快速服务器在端口 5000 上运行,React 在端口 3000 上运行
  • 如果是应用中使用的静态图片,它应该在 react 文件夹中并导入 throw webpack loader。在您的情况下,您将图像存储在数据库中,因此您应该与服务器提供的 react 共享图像文件夹分开
  • 但这不应该是这样,因为如果我将源设置为 PATH 作为字符串,即:src='../images/profilepic.jpg' 我能够看到图片。为什么当我将它设置为分配了相同字符串的变量时不是这种情况?
  • 因为如果您在项目中使用静态图像,您应该导入它们。像 'import ProfilePic from "./images/profilepic.jpg" ' 然后像 '' 一样使用它,这样你就不能使用数据库中的不同图像了。您不能在导入中使用变量
【解决方案2】:
<img src={require(`${profilepic}`)} />

我认为你只需要模板文字

【讨论】:

  • 这会产生以下错误:Cannot find module '../images/profile.jpg'
【解决方案3】:

要访问本地图像路径,您还需要在环境变量中添加 NODE_PATH=src 或将其附加到 package.json 文件中的启动键脚本中,如下所示。

"start": "NODE_PATH=src react-scripts start",

【讨论】:

  • 我在 package.json 文件中的启动脚本中添加了上述行,但在尝试启动应用程序时出现此错误:'NODE_PATH' 不被识别为内部或外部命令、可运行程序或批处理文件。我是否必须将其添加到我的环境变量中,如果我应该怎么做,我是创建一个新的环境变量还是编辑一个现有的环境变量?
  • 试试这个 export NODE_PATH=src; npm 开始;
  • 你可以在你的环境文件中创建一个新变量
【解决方案4】:

试试这个:

import Image from "filePath/imgName";

您可以在任何代码行中使用此图标。例如:

<img src={Image}/>

【讨论】:

  • 这只有在您已经知道图像的路径时才有效,图像路径存储在数据库中并且每个用户都有与其个人资料图片相关联的不同路径,因为每个用户都有不同的个人资料图片.
  • 我已经从数据库中获得了图像路径,对于这个用户来说它是:'../images/profile.jpg' 我已经将它保存到一个状态变量但是当我将它添加为 src到我的图片标签,我在网站上看不到图片。
【解决方案5】:

基本上,您已经编写了正确的代码&lt;img src={profilepic} alt="myprofilepic"/&gt; 但问题是你没有 API 来打开这个文件像这样:

const openFile = (req, res, next) => {
    File.findOne({ _id: req.params.id,path:req.params.path }, function(err, users) {
        if (err) {
            return res.status(400).json({
                error: errorHandler.getErrorMessage(err)
            });
        }
        console.log(users);
        console.log(users.path);

    });
};

//route of this controller***
router.route('/api/openfile/:id')

您可以打开文件

<img={`http://localhost/api/openfile/${profilepic}`}/>

【讨论】:

  • 嗨 Vijay 我很难理解这一点。我已经从数据库中获得了文件的路径,在使用 axios 获取图像后,图像的路径是“../images/profile.jpg”,然后将其保存到变量 profilepic 中。然后,当我设置 img src={profilepic} 时,我无法在网站上看到图像。但是如果我设置 src=require(${../images/profilepic.jpg}) 我可以看到图像
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-10
  • 2017-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
相关资源
最近更新 更多