【问题标题】:Browser does not show the src Image in React浏览器在 React 中不显示 src 图像
【发布时间】:2022-01-27 05:46:40
【问题描述】:

嘿,我正在创建一个上传图像系统。但是当我的后端返回 imagePath 并且我在 src 上的 React useState 中管理路径时,图像没有显示,并且控制台抛出以下错误:

这是我在 React 中的 package.json:

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:3000",
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.25.0",
    "bootstrap": "^5.1.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

我的后端在 3000 端口上运行,而 React 在 3001 端口上运行。

这是我的 React 代码:

import { useState } from "react";
import axios from 'axios';
import {Message} from './Message.js';
import {ProgressBar} from './ProgressBar.js';


export const App = () => {

  const [file, setFile] = useState('');
  const [fileName, setFileName] = useState('Choose a file');
  const [uploadedFile, setUploadedFile] = useState({});
  const [message, setMessage] = useState('No file uploaded');
  const [uploadPercentage, setUploadPercentage] = useState(0);

  const handleChange = (e) => {
    setFile(e.target.files[0]);
    setFileName(e.target.files[0].name);
  }

  const handleSubmit = async (e) => {
    e.preventDefault();

    const formData = new FormData();
    formData.append('file', file);

    try {
      const res = await axios.post('/uploadImage', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: ProgressEvent => {
          setUploadPercentage(
            parseInt(
              Math.round( (ProgressEvent.loaded * 100) / ProgressEvent.total )
            )
          );
        setTimeout(() => {
          setUploadPercentage(0);
        }, 10000);
        }
      })

      const {fileName, filePath} = res.data;
      
      //return from res.data = /Users/rodrigoroldan/Desktop/Programacion/ImageUploader/client/public/uploads/sktwif5gkyvo0o92.png
      
      setUploadedFile({fileName, filePath});
      setMessage('File Uploaded');

    } catch (error) {
      if(error.response.status === 500){
        setMessage('There was a problem with the server');
      } else{
        setMessage(error.response.data.msg);
      }
    }

  }


  return (
    <div className="container text-center d-flex flex-column">
      <h1 className="display-2">Image uploader</h1>
      {message && <Message msg={message}/> }
      <form className="form d-flex flex-column" onSubmit={handleSubmit}>
        <ProgressBar percentage={uploadPercentage} />
        <input type="file" accept="image/*" name="image" onChange={handleChange}/>
        <button className="btn btn-primary" onClick={handleSubmit}>Upload</button>
      </form>

      <label className="label">
        {fileName}
      </label>

      {
        uploadedFile
        &&
        <div className="row mt-5">
          <div className="col-md-6 m-auto">
            <img src={uploadedFile.filePath} alt={uploadedFile.fileName} style={{width:'100%'}} />
          </div>
        </div>
      }
    </div>
  );
}

谢谢!

【问题讨论】:

    标签: node.js reactjs src


    【解决方案1】:

    我可以在屏幕截图中看到,您的代码在您的 React 应用程序中寻找路径,而它必须在您的后端(端口 3000)中搜索。说明你的文件路径不对。

    您必须在后端服务器中存储和公开图像,然后通过转换以下行来显示图像: &lt;img src={uploadedFile.filePath} alt={uploadedFile.fileName} style={{width:'100%'}} /&gt;

    &lt;img src={`${process.env.REACT_APP_BACKEND_URI}${uploadedFile.filePath}`} alt={uploadedFile.fileName} style={{width:'100%'}} /&gt;

    使用 REACT_APP_BACKEND_URI 作为环境变量(在您的情况下,它是 localhost:3000)和 uploadFile.filePath 是您将图像保存在后端而不是本地文件位置的路径(它似乎是文件位置您的计算机,而不是服务器上的位置)。完成此操作后,html 将使用您的文件路径搜索文件的位置,但在后端,如果存在,则会显示它,否则您将遇到 404 错误。

    【讨论】:

    • 好的,也许我的问题是后端将图像保存在我的 React 代码所在的“客户端”文件夹内的公用文件夹中。我尝试使用相对位置...但我发现保存在该文件夹中的唯一方法是使用以下代码:` const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const pathUploads = path.resolve(__dirname, './client/public/uploads'); ` 并返回本地路径
    • 您的后端必须将文件保存在它可以访问的文件夹中。例如,如果您使用 django 后端,则可能会有一个“媒体”文件夹,您可以在其中放置文件然后提供它们。
    【解决方案2】:

    我通过使用以下几行更改 filePath 来解决:

    const filePathSplit = filePath.split('/');
    const newNameFile = filePathSplit[filePathSplit.length - 1]
    const newFilePath = `/uploads/${newNameFile}`
    
    

    而我的img 标签是:

    &lt;img src={uploadedFile.newFilePath} alt={uploadedFile.fileName} style={{width:'100%'}} /&gt;

    【讨论】:

      猜你喜欢
      • 2021-10-02
      • 2021-11-25
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 2013-04-15
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多