How to create an ArrayBuffer and data URI from Blob and File objects without FileReader?
这个问题与如何在旧浏览器(例如 Safari 5.1.4)中更新有关并受到启发
给定一个具有
目前尝试过的方法是
-
创建一个模拟
WebSocket 并将.binaryType 设置为"arraybuffer" ,创建一个MessageEvent 并将event.data 设置为File 对象;结果是onmessage handler处的
File 对象 -
将
File 的原型设置为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]() -
在
FormData 对象上设置File ,尝试将请求正文发布到<iframe> ,诚然没有很好的构思;结果Bad Request 在 plnkr
预期结果:将
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <!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"></iframex> 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; } </body> </html> |
另请参阅使用 javascript 和 websockets 从 blob 显示图像,如何在 JavaScript 中将字符串编码为 Base64? ;有趣的是,我现在在问类似的问题 https://stackoverflow.com/questions/34302231/is-there-any-way-to-convert-the-file-to-an-arraybuffer-without-filereader-api ;
我只是放在这里:
1 2 3 4 5 6 7 8 9 10 11 | var input = document.querySelector("input[type=file]"); input.addEventListener("change", handleFiles, true); // for url window.URL = window.URL || window.webkitURL; function handleFiles(evnet) { var file = event.target.files[0]; document.querySelector('iframe') .setAttribute('src', window.URL.createObjectURL(file)); } |
1 2 3 4 5 6 7 8 9 10 11 12 | <!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"></iframex> </body> </html> |