js图片网络地址转file文件

js图片网络地址转file文件

//图片地址转base64格式
    imgToBase64(url,cb){
      var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d'),
      img = new Image;
      
      img.crossOrigin = 'Anonymous';
      img.onload = function () {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL('image/png');
        cb && cb(dataURL);
        canvas = null;
      };
      img.src = url;
    },
    //base64转file对象
    base64toFile(base, filename){
      var arr = base.split(',');
      var mime = arr[0].match(/:(.*?);/)[1];
      var suffix = mime.split("/")[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      //转换成file对象
      return new File([u8arr], `${filename}.${suffix}`, { type: mime });
    },
	//使用
	this.imgToBase64(imgUrl,base =>{
	   file = this.base64toFile(base,'图片')
	 })
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用uni-app的`uni.downloadFile` API来实现将网络图片为本地临时文件,具体实现步骤如下: 1. 使用`uni.downloadFile`下载网络图片,例如: ```javascript uni.downloadFile({ url: 'http://example.com/image.png', success: function (res) { console.log('downloadFile success, res', res) }, fail: function (err) { console.log('downloadFile fail, err', err) } }) ``` 2. 在`success`回调中,获取下载后的临时文件路径`tempFilePath`,并将其用作图片的src属性,例如: ```javascript uni.downloadFile({ url: 'http://example.com/image.png', success: function (res) { console.log('downloadFile success, res', res) // 将下载后的临时文件路径tempFilePath作为图片的src属性 const tempFilePath = res.tempFilePath this.imageSrc = tempFilePath }, fail: function (err) { console.log('downloadFile fail, err', err) } }) ``` 3. 如果需要将临时文件保存到本地永久存储,可以使用`uni.saveFile` API将其保存到本地,例如: ```javascript uni.downloadFile({ url: 'http://example.com/image.png', success: function (res) { console.log('downloadFile success, res', res) // 将下载后的临时文件路径tempFilePath作为图片的src属性 const tempFilePath = res.tempFilePath this.imageSrc = tempFilePath // 将临时文件保存到本地永久存储 uni.saveFile({ tempFilePath: tempFilePath, success: function (res) { console.log('saveFile success, res', res) // 保存成功后,可以使用res.savedFilePath获取本地文件路径 }, fail: function (err) { console.log('saveFile fail, err', err) } }) }, fail: function (err) { console.log('downloadFile fail, err', err) } }) ``` 需要注意的是,临时文件在小程序被关闭或卸载后会被清除,如果需要长期保存文件,应该将其保存到本地永久存储。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值