浏览器控制台在 'FileReader' 上显示 readAsBinaryString':参数 1 不是 'Blob' 类型

browser console says readAsBinaryString' on 'FileReader': parameter 1 is not of type 'Blob'

 getFiletoValidate = () => {
 const fName = this.props.fileName;
 const selectFile = this.props.selectedFile;
 const inputValue = this.fileInput.value;
 const providernameId = this.props.endL4;
 const messsageTypeId = this.props.endType;

 var read = new FileReader();
 read.readAsBinaryString(selectFile);

if (inputValue === "") {
  window.Notification.showWarning("Warning,Please choose a file to      validate");
} else 
{

  setTimeout(function() {
    api.messageValidator(fName, providernameId, messsageTypeId, read.result,this.handleFileSuccessResponse,this.handleFileFailResponse);
    }, 2000);        
}}

我使用 readAsBinaryString 获取文件数据,但问题是浏览器控制台在 'FileReader' 上显示 readAsBinaryString':参数 1 不是 'Blob' 类型。有哪位帮忙解决

我假设您的 api 调用发生在完全读取文件之前。所以你可以通过设置超时轻松解决这个问题,但你已经完成了。

我想你错过了这个 statement.Please 试试这个代码它应该有效

getFiletoValidate = () => {
  const fName = this.props.fileName;
  const selectFile = this.props.selectedFile;
  const inputValue = this.fileInput.value;
  const providernameId = this.props.endL4;
  const messsageTypeId = this.props.endType;

  var read = new FileReader();
  read.readAsBinaryString(selectFile);

 if (inputValue === "") {
    window.Notification.showWarning("Warning,Please choose a file to validate");
}else 
{

 setTimeout(function() {
   api.messageValidator(fName, providernameId, messsageTypeId,read.result,self.handleFileSuccessResponse,self.handleFileFailResponse);
}, 2000);        
  }
}

问题是 javascript 是异步的,因此在您的代码中 api 调用在完全读取文件之前命中。 Settimeout 是处理此问题的一个选项,但它不是推荐的选项,因为文件大小很小,您的超时 2s 是可以的。想想如果一个大文件需要超过 2 秒来读取内容......会发生什么......应该为 read.result 传递一个空值 所以你需要尝试一个同步方法来处理像

var fs = require("fs");
fs.readFileSync(‘abc.txt’,function(err,data){
if(!err) {
console.log(data);
}
 });
console.log("something else");

在此之前需要安装文件流npm并输入fs

是的,我都同意。在我看来,使用同步方法不是一个好的选择,因为 think

  1. 如果您的输入文件损坏,您的代码就会卡在该文件中 reader 代码快照,这就是您的页面毫无问题地损坏的原因
  2. 如果有人输入了一个像 2GB 这样的大文件,那么您要等那么久 time.It 不是一个好的选择,因为您的性能很差

所以更好的选择是您需要使用您选择的任何方法对文件大小进行前端验证