本文介绍了如何使以下readAsDataURL返回多个readAsDataURL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此函数读取从输入字段获取的文件并返回其dataUrl:

This function read files gotten from an input field and return their dataUrls:

readAsDataURL (target) {
  // target => <input type="file" id="file">
  var reader = new FileReader()
  return new Promise(function (resolve, reject) {
    reader.onload = function (event) {
      resolve(event.target.result)
    }
    reader.readAsDataURL(target.files[0])
  })
},

如您所见,该功能仅处理单个文件.我想返回多个文件.我尝试做reader.readAsDataURL(target.files),但收到此错误:'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

As you can see, the function only deals with single files. I want to return multiple files. I tried doing reader.readAsDataURL(target.files) but got this error: 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

如何使函数返回多个dataUrl?

How to make the function return multiple dataUrls?

推荐答案

您是否尝试过使用 Promise.all ?您可能可以执行以下操作:

Have you tried using Promise.all? You might be able to do something like:

fileToDataURL(file) {
  var reader = new FileReader()
  return new Promise(function (resolve, reject) {
    reader.onload = function (event) {
      resolve(event.target.result)
    }
    reader.readAsDataURL(file)
  })
}  

readAsDataURL (target) {
  // target => <input type="file" id="file">
  var filesArray = Array.prototype.slice.call(target.files)      
  return Promise.all(filesArray.map(fileToDataURL))
}

这基本上与您设置的功能相同,但是会为每个对象创建一个承诺,仅在全部完成后才将结果返回到数组中.

This essentially does the same thing you had setup, but creates a promise for each one, returning the result in an array only once all have been completed.

我忘记了您不能直接将target.files视为数组,因此需要首先对其进行转换.为此,您可以使用:Array.prototype.slice.call(target.files)

I forgot that you cannot treat target.files directly as an array, so it needs to be converted first. For this you can use: Array.prototype.slice.call(target.files)

这篇关于如何使以下readAsDataURL返回多个readAsDataURL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 07:12