★ 背景说明
| 在浏览器环境中,由于安全性限制,不能直接将网络图片地址转换成 File 对象。File 对象是用户在客户端上传文件时才能创建的,而不能由前端代码直接将网络图片地址转换成 File 对象。 |
★ 解决方案
| 如果你想要将网络图片地址转换成 Fie 对象,你需要先将图片下载到客户端,然后再将其转换为 File 对象。这可以通过以下步骤完成: |
| 1. 使用 Axios(或其他网络请求库)下载图片数据。 |
| 2. 将下载的数据转换成 Blob 对象。 |
| 3. 创建一个新的 File 对象,将 Blob 对象放入其中。 |
★ 功能封装
| |
| async function imageUrlToFile(url, fileName) { |
| try { |
| |
| const response = await axios.get(url, { responseType: 'arraybuffer' }) |
| const imageData = response.data |
| |
| |
| const blob = new Blob([imageData], { |
| type: response.headers['content-type'] |
| }) |
| |
| |
| 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> |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| (async () => { |
| |
| async function imageUrlToFile(url, fileName) { |
| try { |
| |
| const response = await axios.get(url, {responseType: 'arraybuffer'}) |
| const imageData = response.data |
| |
| |
| const blob = new Blob([imageData], { |
| type: response.headers['content-type'] |
| }) |
| |
| |
| 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') |
| |
| const fileUrl = URL.createObjectURL(file) |
| console.log(file, fileUrl) |
| })() |
| </script> |
| </body> |
| </html> |
★ 结果分析
| File {name: 'girl', lastModified: 1719682659397, lastModifiedDate: Sun Jun 30 2024 01:37:39 GMT+0800 (中国标准时间), webkitRelativePath: '', size: 185786, …} |
| blob:http: |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· PPT革命!DeepSeek+Kimi=N小时工作5分钟完成?
· What?废柴, 还在本地部署DeepSeek吗?Are you kidding?
· DeepSeek企业级部署实战指南:从服务器选型到Dify私有化落地
· 程序员转型AI:行业分析
· 重磅发布!DeepSeek 微调秘籍揭秘,一键解锁升级版全家桶,AI 玩家必备神器!