0

我只是想知道如何从 html 输入文件中获取字节数组。

代码如下:

  <script type ="text/javascript">            

        $(document).ready(function() {

            $('#cmdUpload').click(function() {

                uploadFile();

            });

            function uploadFile() {

                var file = $("#objFile")[0].files[0];




            }
        });
    </script>
      <body>
     <input type ="file" id="objFile" size="50" /><br/><br/>
     <input type ="button" id="cmdUpload"  value="Upload"/>
    </body>

非常感谢

4

1 回答 1

3

这是返回字节的示例代码:

$(document).ready(function() {
  $('#cmdUpload').click(function() {
    uploadFile();
  });

});

function uploadFile() {
  var input = document.getElementById('objFile');
  // var file = $("#objFile")[0].files[0];
  var file = input.files[0];
  fr = new FileReader();
  fr.onload = receivedText;
  //fr.readAsText(file);
  fr.readAsDataURL(file);
}

function receivedText() {
  var b64Data = fr.result.split(',');
  var contentType = 'image/jpeg';
  //document.getElementById('editor').appendChild(document.createTextNode(fr.result))
  var byteCharacters = atob(b64Data[1]);
  var byteNumbers = Array.prototype.map.call(byteCharacters,
    charCodeFromCharacter);
  var uint8Data = new Uint8Array(byteNumbers);
  var blob = b64toBlob(b64Data[1], contentType);
  var blobUrl = URL.createObjectURL(blob);
}

function charCodeFromCharacter(c) {
  return c.charCodeAt(0);
}

function b64toBlob(b64Data, contentType, sliceSize) {
  contentType = contentType || '';
  sliceSize = sliceSize || 1024;
  var byteCharacters = atob(b64Data);
  var byteArrays = [];

  for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    var slice = byteCharacters.slice(offset, offset + sliceSize);
    var byteNumbers = Array.prototype.map.call(slice, charCodeFromCharacter);
    var byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }
  for (var i = 0; i < byteArray.length; i++) {
    alert(byteArray[i]);
  }

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <input type="file" id="objFile" size="50" /><br />
  <br />
  <input type="button" id="cmdUpload" value="Upload" />
  <div id="editor"></div>
</div>

希望它会帮助你。请让我知道以获得进一步的帮助。

于 2013-09-25T06:34:24.090 回答