我需要创建一个方法,用AJAX将图像转换为ByteArray,然后通过AJAX发送到My API PHP。
有人可以帮助我吗?!
由于
答案 0 :(得分:0)
解决方案1:
这是返回字节的示例代码
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>
注意:需要Jquery库。
希望它会对你有所帮助。
解决方案2:
参考链接: