JavaScript FileReader读取文件错误 [英] Javascript FileReader reads file incorrectly

查看:662
本文介绍了JavaScript FileReader读取文件错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简短的JavaScript函数,它将获取一个上传的文件并显示它的十六进制等效项.比较原始文件和十六进制编辑器中的输出,可以发现它们部分不同,但不完全相同.

I have a short JavaScript function which will take an uploaded file and display the hex equivalent of it. Comparing the original file and the output in a hex-editor shows that they are partially different but not completely.

String.prototype.hexEncode = function(){
  var hex, i;

  var result = "";
  for (i = 0; i < this.length; i++) {
    hex = this.charCodeAt(i).toString(16);
    result += ("" + hex).slice(-4);
  }

  return result
}

function upload() {
  var file = document.getElementById("fileToUpload").files[0];
  var reader = new FileReader();
  reader.readAsText(file, "windows-1252");
  reader.onload = function (evt) {
    var program = evt.target.result.hexEncode();
    program = program;
    console.log(program);
  }
}

以下是原始文件和彼此相邻的输出:

Here are the original file and the output next to each other:

2A 2A 54 49 38 33 46 2A 1A 0A 0A 43 72 65 61 74
2A 2A 54 49 38 33 46 2A 1A AA 43 72 65 61 74 65

是什么导致输出差异?任何帮助将不胜感激.

What is causing the difference in outputs? Any help would be greatly appreciated.

推荐答案

要在js中生成十六进制转储,您将不想使用readAsText方法,该方法将以UCS-2或UTF格式转换您的数据而是改为-16,直接从

To generate an Hex dump in js, you won't want to use the readAsText method, which will convert your data in either UCS-2 or UTF-16, instead, read directly the binary data you'll get from the readAsArrayBuffer method, and work from there:

function hexDump(file) {
  return new Promise((res, rej) => {
    if (!(file instanceof Blob)) rej('wrong input');
    const reader = new FileReader();
    reader.onload = e => {
      res(hex(reader.result));
    };
    reader.onerror = e => rej('error while reading');
    reader.readAsArrayBuffer(file);
  });
  // gotten from https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#Example
  function hex(buffer) {
    const hexCodes = [];
    const view = new DataView(buffer);
    for (let i = 0; i < view.byteLength; i += 4) {
      // Using getUint32 reduces the number of iterations needed (we process 4 bytes each time)
      let value = view.getUint32(i)
      // toString(16) will give the hex representation of the number without padding
      let stringValue = value.toString(16)
      // We use concatenation and slice for padding
      let padding = '00000000'
      let paddedValue = (padding + stringValue).slice(-padding.length).toUpperCase();
      hexCodes.push( // simple prettyfying
        paddedValue.slice(0,2),
        paddedValue.slice(2,4),
        paddedValue.slice(4,6),
        paddedValue.slice(6,8)
        );
    }
    return hexCodes.join(' ');
  }
}

// How to use it
inp.onchange = e => hexDump(inp.files[0].slice(0, 100)) // for demo I slice the file
    .then(hex => console.log(hex))
    .catch(e => console.error(e));

<input type="file" id="inp">

这篇关于JavaScript FileReader读取文件错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆