★ 背景说明

在浏览器环境中,由于安全性限制,不能直接将网络图片地址转换成 File 对象。File 对象是用户在客户端上传文件时才能创建的,而不能由前端代码直接将网络图片地址转换成 File 对象。

★ 解决方案

如果你想要将网络图片地址转换成 Fie 对象,你需要先将图片下载到客户端,然后再将其转换为 File 对象。这可以通过以下步骤完成:
1. 使用 Axios(或其他网络请求库)下载图片数据。
2. 将下载的数据转换成 Blob 对象。
3. 创建一个新的 File 对象,将 Blob 对象放入其中。

★ 功能封装

// 将网络图片地址转换为File对象
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步:使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' })
    const imageData = response.data

    // 第二步:将图片数据转换为Blob对象
    const blob = new Blob([imageData], {
      type: response.headers['content-type']
    })

    // 第三步:创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type })

    return file
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error)
    throw error
  }
}

★ 代码示例

<!doctype html>
<html>
<head>
    <title>网络图片地址转换为File对象</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
    /*
    关于在script中使用await的语句报错的解决说明:
        commonjs规范无法像ES模块直接使用顶层await,必须搭配async关键字使用
    解决办法: 将使用await的语句,用 (async () =>())() 的自执行函数包裹起来
        (async () => {
          const config = {...}
          await esbuild.context(config);
        })();
    */
    (async () => {
        // 将网络图片地址转换为File对象
        async function imageUrlToFile(url, fileName) {
            try {
                // 第一步:使用axios获取网络图片数据
                const response = await axios.get(url, {responseType: 'arraybuffer'})
                const imageData = response.data

                // 第二步:将图片数据转换为Blob对象
                const blob = new Blob([imageData], {
                    type: response.headers['content-type']
                })

                // 第三步:创建一个新的File对象
                const file = new File([blob], fileName, {type: blob.type})

                return file
            } catch (error) {
                console.error('将图片转换为File对象时发生错误:', error)
                throw error
            }
        }

        const imgUrl = 'https://gips3.baidu.com/it/u=3886271102,3123389489&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960'
        const file = await imageUrlToFile(imgUrl, 'girl')
        console.log(file)
    })()
</script>
</body>
</html>

★ 结果分析

File {name: 'girl', lastModified: 1719682659397, lastModifiedDate: Sun Jun 30 2024 01:37:39 GMT+0800 (中国标准时间), webkitRelativePath: '', size: 185786, …}