我只是想知道如何从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>
非常感谢
答案 0 :(得分:2)
这是返回字节的示例代码
Javascript:
<script type="text/javascript">
$(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>
HTML:
<div>
<input type="file" id="objFile" size="50" /><br />
<br />
<input type="button" id="cmdUpload" value="Upload" />
<div id="editor"></div>
</div>
希望它会对你有所帮助。如果有进一步的帮助,请告诉我。