« Back to home

Javascript Load File Data

Javascript is designed to disallow file loading of any kind unless the file is chosen by the user. That means if you want to load, for example, an image file from a remote url and read the file data, it's not possible. However, that can be easily achieved with the help of a server-side script that does the file loading and returns the loaded data to Javascript. For example in Rails, we can do something like:

url = params[:url]
base64 = ActiveSupport::Base64.encode64s(open(url) { |io| io.read })
render :json => {:base64 => base64}

The script returns the base64 data representation of the file in json format. The file url is passed in as a query parameter. Then in Javascript, after getting the file data, we can decode the base64 data into binary. The Base64Binary library is perfect for this purpose:

var binary = Base64Binary.decode(base64)

Note that the Base64Binary.decode() method doesn't automatically recognizes the equal signs at the end of the base64 string used for padding. It will take the equal signs as part of the binary stream which will result to incorrect decoding. To prevent that, we have to explicitly escape the equal signs:

base64 = base64.replace('=', '%3D');

The binary result is encapsulated in a Uint8Array object which you can use for file uploading or some other binary operations.


comments powered by Disqus