How to create an ArrayBuffer and data URI from Blob and File objects without FileReader?

匿名 (未验证) 提交于 2019-12-03 01:25:01

问题:

This Question is related to and inspired by How to updoad in old browsers (ex Safari 5.1.4)

Given an element having a files property containing File objects which inherit from Blob, is it possible to create a ArrayBuffer and convert the ArrayBuffer to a data URI from a Blob or File object without using FileReader?

Approaches have tried so far have been

  • create a mock WebSocket with .binaryType set to "arraybuffer", create a MessageEvent with event.data set to File object; result is File object at onmessage handler

  • set prototype of File to ArrayBuffer, Uint8Array; result is Uncaught TypeError: Method ArrayBuffer.prototype.byteLength called on incompatible receiver #(), Uncaught TypeError: Method get TypedArray.prototype.byteLength called on incompatible receiver [object Object]()

  • set File at FormData object, attempt to post request body to , admittedly not well-conceived; result Bad Request at plnkr

Expected result: Convert Blob and File objects to TypedArray then to data URL, or directly to data URL

         

See also Display image from blob using javascript and websockets , How can you encode a string to Base64 in JavaScript? ; interestingly ironic as am now asking similar Question https://stackoverflow.com/questions/34302231/is-there-any-way-to-convert-the-file-to-an-arraybuffer-without-filereader-api ; Blob .slice() method , FileReader .readAsDataURL() method

回答1:

Can try createObjectURL() if it supports

URL.createObjectURL() static method creates a DOMString containing an URL representing the object given in parameter , you can get url of whatever image,document the user uploads but if its binary it will simply start download

var files = fileupload.files;  //get all files  for (var i = 0; file = files[i]; i++)      url= window.URL.createObjectURL(file); //gives url to files you can embed  

https://jsfiddle.net/y2u6hzb7/

it only creates link and not bin array so to see txt open the link in new tab.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!