You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React点击按钮加载目录静态图片时createObjectURL报错如何解决

报错原因
  • URL.createObjectURL() 仅接受 Blob、File、MediaSource 三类参数,你传入的是自定义的普通对象,参数类型不匹配导致报错
  • 你通过import引入的静态图片资源只是打包后的路径字符串,不是二进制文件对象,无法直接用于上传接口调用
修复方案

你需要先将静态图片路径转换为真实的File对象,既可满足展示需求,也可以直接用于后续Django接口上传。以下是完整修改后的代码:

import React, {Component} from 'react';
import image_1 from "../../static_media/1.png"
import image_2 from "../../static_media/2.png"
import {Container, Image} from "react-bootstrap";


class Classifier extends Component {
    state = {
        files: [],
        isLoading: false,
        recentImage: null,
        // 新增存储真实File对象的关联字段
        imageFile: null
    }

    // 新增:将静态图片路径转为File对象的工具方法
    urlToFile = async (url, filename, mimeType = 'image/png') => {
        const response = await fetch(url);
        const blob = await response.blob();
        return new File([blob], filename, {type: mimeType});
    }

    handleClick = async (e) => {
        const ImageData = [image_1, image_2]
        // 先构造图片基础信息
        const FILES = {
            "image_1": {
                name: "image_1.png",
                size: "100",
                url: ImageData[0]
            },
            "image_2": {
                name: "image_2.png",
                size: "200",
                url: ImageData[1]
            },
            "image_3": {
                name: "image_3.png",
                size: "300",
                url: ImageData[1]
            },
        }

        const prefix = e.target.dataset.prefix;
        const targetImg = FILES[`image_${prefix}`];
        this.setState({
            files: [],
            isLoading: true,
            recentImage: null,
            imageFile: null
        })
        // 转换为真实File对象
        const file = await this.urlToFile(targetImg.url, targetImg.name);
        this.loadImage([{...targetImg, rawFile: file}])
    }

    loadImage = (files) => {
        setTimeout(() => {
            this.setState({
                files,
                isLoading: false
            })
        }, 1000);
    }

    // 组件卸载时释放objectURL占用的内存,避免内存泄漏
    componentWillUnmount() {
        if (this.state.files.length > 0) {
            URL.revokeObjectURL(this.state.files[0].rawFile);
        }
    }

    render() {
        const files = this.state.files.map(file => (
            <li key={file.name}>
                {file.name} - {file.size} bytes
            </li>
        ));
        return (
            <Container>
                <button
                    data-prefix="1"
                    onClick={(e) => this.handleClick(e)}
                    className="btn btn-primary">
                    Sample 1
                </button>
                <aside>
                    {files}
                </aside>

                <div className="img-fluid">
                    {this.state.files.length > 0 &&
                    <Image
                        // 用转换后的真实File对象生成objectURL,也可以直接用file.url静态路径展示
                        src={URL.createObjectURL(this.state.files[0].rawFile)}
                        height='400' rounded/>
                    }
                </div>
            </Container>
        )
    }
}

export default Classifier;
上传到Django REST API用法

后续需要上传时,直接把rawFile放到FormData中提交即可:

const formData = new FormData();
// 第二个参数要和Django接口接收的文件字段名对应
formData.append('upload_image', this.state.files[0].rawFile);
// 调用接口时指定请求头 Content-Type: multipart/form-data 即可正常上传

内容的提问来源于stack exchange,提问作者Joseph Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:45:05