首页 > 解决方案 > 如何检查路径中是否真的有图像?

问题描述

我正在开发一个反应系统,一会儿我必须显示用户的头像,如果用户没有注册图像,那么我显示一个标准图像。

问题是,有时用户有一个已经在数据库中注册的图像的 URL,例如: path_img: 'http://localhost: 3000 / file/1asd-0a9f-asdaf90-asf9a-fa.png' 。

但是,访问此地址时,找不到图像。

怎么可能知道这个链接是否有效?也就是说,它有一个现有的图像吗?

    async componentDidMount() {
        const user = JSON.parse(getUserToken());
        console.log(user);
        if (user.logo_path) {
            user.logo_path = `http://localhost:3333/files/${user.logo_path}`;

            // check if the image in that logo_path really exists
        
        }
        else
            user.logo_path = 'https://cdn.icon-icons.com/icons2/1378/PNG/512/avatardefault_92824.png';

        await this.setState({ user });

        this.handlePermissions();
    }

标签: reactjs

解决方案


在我的世界中,如果来自链接的 img 的加载失败,则可以加载标准图片;-)

因此,您不必知道链接是否损坏,但您现在可以清除数据库中损坏的链接。

LoadStandardpic 如果链接断开并在数据库中清除它。


推荐阅读