Javascript 通过输入类型=文件获取字节数组

Javascript 通过输入类型=文件获取字节数组,javascript,html,fileapi,Javascript,Html,Fileapi,var profileImage=fileInputInByteArray; $.ajax({ 网址:abc.com/, 键入:“POST”, 数据类型:“json”, 数据:{ //其他数据 ProfileImage:ProfileImage //其他数据 }, 成功:{ } }) //WebAPI中的代码 [HttpPost] 公共HttpResponseMessageUpdateProfile([FromUri]UpdateProfileModel响应){ //... 返回响应; } 公共

var profileImage=fileInputInByteArray;
$.ajax({
网址:abc.com/,
键入:“POST”,
数据类型:“json”,
数据:{
//其他数据
ProfileImage:ProfileImage
//其他数据
},
成功:{
}
})
//WebAPI中的代码
[HttpPost]
公共HttpResponseMessageUpdateProfile([FromUri]UpdateProfileModel响应){
//...
返回响应;
}
公共类UpdateProfileModel{
// ...
公共字节[]ProfileImage{get;set;}
// ...
}
[编辑] 如上所述,尽管仍在一些UA实现中,
readAsBinaryString
方法没有进入规范,不应在生产中使用。 相反,使用
readAsArrayBuffer
并循环通过它的
缓冲区
,以获取二进制字符串:

document.querySelector('input').addEventListener('change',function(){
var reader=new FileReader();
reader.onload=函数(){
var arrayBuffer=this.result,
阵列=新的UINT8阵列(arrayBuffer),
binaryString=String.fromCharCode.apply(null,数组);
log(二进制字符串);
}
reader.readAsArrayBuffer(this.files[0]);
},假)

$(文档).ready(函数(){
(职能(文件){
var input=document.getElementById(“文件”),
输出=document.getElementById(“结果”),
fileData;//我们需要fileData对getBuffer可见。
//用于文件输入的Eventhandler。
函数openfile(evt){
var files=input.files;
//将文件传递给blob,而不是输入[0]。
fileData=newblob([files[0]]);
//将getBuffer传递给promise。
var承诺=新承诺(getBuffer);
//等待承诺得到解决,或记录错误。
promise.then(函数(数据){
//在这里,您可以将字节传递给另一个函数。
output.innerHTML=data.toString();
控制台日志(数据);
}).catch(函数(err){
log('Error:',err);
});
}
/* 
创建一个将传递给promise的函数
并在FileReader加载完文件后解决此问题。
*/
函数getBuffer(解析){
var reader=new FileReader();
reader.readAsArrayBuffer(文件数据);
reader.onload=函数(){
var arrayBuffer=reader.result
var字节=新的Uint8Array(arrayBuffer);
解析(字节);
}
}
//用于文件输入的Eventlistener。
input.addEventListener('change',openfile,false);
}(文件);
});

这是一篇很长的文章,但我厌倦了所有这些对我不起作用的示例,因为它们使用了Promise对象或错误的
这篇
,在使用Reactjs时有不同的含义。我的实现使用了一个带有reactjs的DropZone,我使用一个类似于以下站点发布的框架获得了字节,而上面的其他内容都不起作用:。有两把钥匙,是给我的:

  • 您必须使用FileReader的onload函数并在其运行期间从事件对象获取字节
  • 我尝试了各种组合,但最终成功的是:

    const bytes=e.target.result.split('base64')[1]

  • 其中
    e
    是事件。React需要
    const
    ,您可以在普通Javascript中使用
    var
    。但这给了我base64编码的字节字符串

    因此,我只想包括一些适用的行来集成它,就好像您在使用React一样,因为我就是这样构建它的,但也尝试对其进行概括,并在必要时添加注释,以使其适用于普通的Javascript实现-请注意,我没有在这样的构造中使用它来测试它

    这些是位于顶部的绑定,在构造函数中,在React框架中(与普通Javascript实现无关):

    在DropZone元素中有
    onDrop={this.uploadFile}
    。如果您在没有React的情况下执行此操作,则这相当于在单击“上载文件”按钮时添加要运行的onclick事件处理程序

    字节
    应具有base64字节

    其他功能:

    结语:

    processFile()
    内部,由于某种原因,我无法将
    字节添加到我在
    this.state
    中创建的变量中。因此,我将其直接设置为变量
    attachments
    ,该变量位于我的JSON对象
    RequestForm
    ——与我的
    this.state使用的对象相同<代码>附件
    是一个数组,因此我可以推送多个文件。事情是这样的:

      const fileArray = [];
      // Collect any existing attachments
      if (RequestForm.state.attachments.length > 0) {
        for (let i=0; i < RequestForm.state.attachments.length; i++) {
          fileArray.push(RequestForm.state.attachments[i]);
        }
      }
      // Add the new one to this.state
      fileArray.push(bytes);
      // Update the state
      RequestForm.setState({
        attachments: fileArray,
      });
    
    从那时起,我可以引用它为
    this.state.attachments
    。在vanilla JS中不适用的React功能。您可以在纯JavaScript中使用全局变量构建类似的构造,并相应地推送,但要容易得多:

    var fileArray = new Array();  // place at the top, before any functions
    
    // Within your processFile():
    var newFileArray = [];
    if (fileArray.length > 0) {
      for (var i=0; i < fileArray.length; i++) {
        newFileArray.push(fileArray[i]);
      }
    }
    // Add the new one
    newFileArray.push(bytes);
    // Now update the global variable
    fileArray = newFileArray;
    
    var fileArray=new Array();//放置在顶部,在任何功能之前
    //在processFile()中:
    var newFileArray=[];
    如果(fileArray.length>0){
    对于(var i=0;i

    然后总是引用
    fileArray
    ,为任何文件字节字符串枚举它,例如
    var myBytes=fileArray[0]

    这是一种将文件转换为Base64的简单方法,可以避免“FileReader.reader.onload超过最大调用堆栈大小”,因为文件的大小很大

    document.querySelector('#fileInput').addEventListener('change',function(){
    var reader=new FileReader();
    var selectedFile=this.files[0];
    reader.onload=函数(){
    var逗号=this.result.indexOf(',');
    var base64=this.result.substr(逗号+1);
    console.log(base64);
    }
    reader.readAsDataURL(selectedFile);
    },假)
    
    uploadFile(event){
        // This is for React, only
        this.setState({
          files: event,
        });
        console.log('File count: ' + this.state.files.length);
    
        // You might check that the "event" has a file & assign it like this 
        // in vanilla Javascript:
        // var files = event.target.files;
        // if (!files && files.length > 0)
        //     files = (event.dataTransfer ? event.dataTransfer.files : 
        //            event.originalEvent.dataTransfer.files);
    
        // You cannot use "files" as a variable in React, however:
        const in_files = this.state.files;
    
        // iterate, if files length > 0
        if (in_files.length > 0) {
          for (let i = 0; i < in_files.length; i++) {
          // use this, instead, for vanilla JS:
          // for (var i = 0; i < files.length; i++) {
            const a = i + 1;
            console.log('in loop, pass: ' + a);
            const f = in_files[i];  // or just files[i] in vanilla JS
    
            const reader = new FileReader();
            reader.onerror = this.errorHandler;
            reader.onprogress = this.progressHandler;
            reader.onload = this.processFile(f);
            reader.readAsDataURL(f);
          }      
       }
    }
    
    processFile(theFile) {
      return function(e) {
        const bytes = e.target.result.split('base64,')[1];
      }
    }
    
    errorHandler(e){
        switch (e.target.error.code) {
          case e.target.error.NOT_FOUND_ERR:
            alert('File not found.');
            break;
          case e.target.error.NOT_READABLE_ERR:
            alert('File is not readable.');
            break;
          case e.target.error.ABORT_ERR:
            break;    // no operation
          default:
            alert('An error occurred reading this file.');
            break;
        }
      }
    
    progressHandler(e) {
        if (e.lengthComputable){
          const loaded = Math.round((e.loaded / e.total) * 100);
          let zeros = '';
    
          // Percent loaded in string
          if (loaded >= 0 && loaded < 10) {
            zeros = '00';
          }
          else if (loaded < 100) {
            zeros = '0';
          }
    
          // Display progress in 3-digits and increase bar length
          document.getElementById("progress").textContent = zeros + loaded.toString();
          document.getElementById("progressBar").style.width = loaded + '%';
        }
      }
    
    <table id="tblProgress">
      <tbody>
        <tr>
          <td><b><span id="progress">000</span>%</b> <span className="progressBar"><span id="progressBar" /></span></td>
        </tr>                    
      </tbody>
    </table>
    
    .progressBar {
      background-color: rgba(255, 255, 255, .1);
      width: 100%;
      height: 26px;
    }
    #progressBar {
      background-color: rgba(87, 184, 208, .5);
      content: '';
      width: 0;
      height: 26px;
    }
    
      const fileArray = [];
      // Collect any existing attachments
      if (RequestForm.state.attachments.length > 0) {
        for (let i=0; i < RequestForm.state.attachments.length; i++) {
          fileArray.push(RequestForm.state.attachments[i]);
        }
      }
      // Add the new one to this.state
      fileArray.push(bytes);
      // Update the state
      RequestForm.setState({
        attachments: fileArray,
      });
    
    this.stores = [
      RequestForm,    
    ]
    
    var fileArray = new Array();  // place at the top, before any functions
    
    // Within your processFile():
    var newFileArray = [];
    if (fileArray.length > 0) {
      for (var i=0; i < fileArray.length; i++) {
        newFileArray.push(fileArray[i]);
      }
    }
    // Add the new one
    newFileArray.push(bytes);
    // Now update the global variable
    fileArray = newFileArray;