这个问题与以下相关并受到启发如何在旧浏览器(例如 Safari 5.1.4)中上传 https://stackoverflow.com/questions/38193605/how-to-updoad-in-old-browsers-ex-safari-5-1-4
给定一个<input type="file">
元素具有files
属性包含File
继承自的对象Blob
,是否可以创建一个ArrayBuffer
并转换ArrayBuffer
to a data URI
from a Blob
or File
不使用对象FileReader
?
迄今为止尝试过的方法有
-
创建一个模拟WebSocket
with .binaryType
set to "arraybuffer"
, 创建一个MessageEvent
with event.data
set to File
目的;结果是File
对象于onmessage
handler
-
设定原型File
to ArrayBuffer
, Uint8Array
;结果是Uncaught TypeError: Method ArrayBuffer.prototype.byteLength called on incompatible receiver #<ArrayBuffer>()
, Uncaught TypeError: Method get TypedArray.prototype.byteLength called on incompatible receiver [object Object]()
-
set File
at FormData
对象,尝试将请求正文发布到<iframe>
,诚然,构思不周全;结果Bad Request
at plnkr http://plnkr.co/edit/Ca7pNsmVhXpv8Us5v8hE?p=preview
预期结果:转换Blob
and File
反对TypedArray
然后到data URL https://www.rfc-editor.org/rfc/rfc2397,或直接到data URL
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="get" entype="multipart/form-data" target="binaryFrame">
<input id="#avatar" type="file" name="file" />
<input type="submit" />
</form>
<iframe name="binaryFrame"></iframe>
<script>
var input = document.querySelector("input[type=file]");
input.addEventListener("change", handleFiles, true);
// see http://jsfiddle.net/adamboduch/JVfkt/
var sock = new WebSocket("ws://mock");
sock.binaryType = "arraybuffer";
sock.onerror = function(e) {
console.log("sock error", e); // ignore, here
}
sock.onmessage = function(e) {
console.log("socket message", e.data, e.data instanceof ArrayBuffer);
};
function handleFiles(evnet) {
var file = event.target.files[0];
sock.dispatchEvent(new MessageEvent("message", {
data: file
}));
var data = new FormData();
data.append("file", file);
document.forms[0].action = data;
}
</script>
</body>
</html>
也可以看看使用 javascript 和 websockets 显示 blob 中的图像 https://stackoverflow.com/questions/11089732/display-image-from-blob-using-javascript-and-websockets , 如何在 JavaScript 中将字符串编码为 Base64? https://stackoverflow.com/questions/246801/how-can-you-encode-a-string-to-base64-in-javascript/;有趣的是,讽刺的是,我现在问类似的问题https://stackoverflow.com/questions/34302231/is-there-any-way-to-convert-the-file-to-an-arraybuffer-without-filereader-api https://stackoverflow.com/questions/34302231/is-there-any-way-to-convert-the-file-to-an-arraybuffer-without-filereader-api ; Blob .slice() method https://w3c.github.io/FileAPI/#slice-method-algo , FileReader .readAsDataURL() method https://w3c.github.io/FileAPI/#readAsDataURL