类型错误:无法设置 null 的属性(设置“src”)

问题描述 投票:0回答:1

我有一个反应代码。它从 django API 获取图像数据并将其显示在屏幕上。图像数据以 base64 格式提供。

import React, { useState } from "react";
import axios from "axios";

function App() {
  const [file, setFile] = useState(null);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [uploadedFile, setUploadedFile] = useState(null);
  const UPLOAD_ENDPOINT = "http://127.0.0.1:8000/api";
  const saveImageLocally = (imageData, fileName) => {
    const base64data = imageData.result;

    const b = document.getElementById("uploaded");

    b.src = `data:image/jpeg;base64,${base64data}`;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (!file) {
        return;
      }

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

      const response = await axios.post(UPLOAD_ENDPOINT, formData, {
        headers: {
          "Access-Control-Allow-Origin": "*",

          "Content-Type": "multipart/form-data",
        },
        onUploadProgress: (progressEvent) => {
          const progress = Math.round(
            (progressEvent.loaded / progressEvent.total) * 100
          );

          setUploadProgress(progress);
        },
      });

      setUploadedFile(response.data);

      setUploadProgress(0); 
      saveImageLocally(response.data, "saved_image.jpg");
    } catch (error) {
      console.error("Error uploading file:", error);
      setUploadProgress(0);
    }
  };

  const handleOnChange = (e) => {
    const selectedFile = e.target.files[0];
    setFile(selectedFile);
    setUploadProgress(0);
    setUploadedFile(null);
  };

  return (
    <div className="container">
      <form onSubmit={handleSubmit} className="upload-form">
        <h1>React File Upload</h1>
        <input type="file" onChange={handleOnChange} />
        <button type="submit" disabled={!file}>
          Upload File
        </button>
        {file && (
          <div className="progress-container">
            <div
              className="progress-bar"
              style={{ width: `${uploadProgress}%` }}
            ></div>
            <span>{uploadProgress}% Uploaded</span>
          </div>
        )}
        {uploadedFile && (
          <div className="uploaded-file">
            <h2>Uploaded File:</h2>
            <p>{uploadedFile.name}</p>
            <img id="uploaded"></img>

            {/* You can display other information about the uploaded file here */}
          </div>
        )}
      </form>
    </div>
  );
}

export default App;

当我运行这个时,它给了我标题中提到的错误。有谁可以帮我解决这个问题吗

Error uploading file: TypeError: Cannot set properties of null (setting 'src')
    at saveImageLocally (Bnw.js:15:1)
    at handleSubmit (Bnw.js:47:1)

我有一些理论,即 DOM 尚未加载。即使我无法修复代码。

javascript reactjs dom
1个回答
0
投票

尝试使用此代码来解决该错误:

import React, { useState, useRef } from "react";
import axios from "axios";

function App() {
  const [file, setFile] = useState(null);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [uploadedFile, setUploadedFile] = useState(null);
  const imgRef = useRef(null); // Here create a ref for the image element
  const UPLOAD_ENDPOINT = "http://127.0.0.1:8000/api";

  const saveImageLocally = (imageData) => {
    const base64data = imageData.result;

    // it checking if imgRef exists before setting the src attribute or not
    if (imgRef.current) {
      imgRef.current.src = `data:image/jpeg;base64,${base64data}`;
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (!file) {
        return;
      }

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

      const response = await axios.post(UPLOAD_ENDPOINT, formData, {
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Content-Type": "multipart/form-data",
        },
        onUploadProgress: (progressEvent) => {
          const progress = Math.round(
            (progressEvent.loaded / progressEvent.total) * 100
          );
          setUploadProgress(progress);
        },
      });

      setUploadedFile(response.data);
      setUploadProgress(0);
      saveImageLocally(response.data);
    } catch (error) {
      console.error("Error uploading file:", error);
      setUploadProgress(0);
    }
  };

  const handleOnChange = (e) => {
    const selectedFile = e.target.files[0];
    setFile(selectedFile);
    setUploadProgress(0);
    setUploadedFile(null);
  };

  return (
    <div className="container">
      <form onSubmit={handleSubmit} className="upload-form">
        <h1>React File Upload</h1>
        <input type="file" onChange={handleOnChange} />
        <button type="submit" disabled={!file}>
          Upload File
        </button>
        {file && (
          <div className="progress-container">
            <div
              className="progress-bar"
              style={{ width: `${uploadProgress}%` }}
            ></div>
            <span>{uploadProgress}% Uploaded</span>
          </div>
        )}
        {uploadedFile && (
          <div className="uploaded-file">
            <h2>Uploaded File:</h2>
            <p>{uploadedFile.name}</p>
            <img ref={imgRef} alt="Uploaded" /> {/* here use ref for the image */}
           
          </div>
        )}
      </form>
    </div>
  );
}

export default App;
© www.soinside.com 2019 - 2024. All rights reserved.