Monday, 16 April 2012

Brief Foray into HTML5 File APIs

Recently, using , I needed to . I couldn't find an easy way to do this within the library. Instead I used the to read the file in and simply send the file contents as part of the payload.

It turns out this is quite easy to do, although a bit verbose. You need to:
  1. Create a FileReader.
  2. Set an event handler for the onload event.
  3. Pass the file(s) you want to read to the appropriate reading method.
For a canned solution, this view for  will allow you to bind an attribute to the content of a file specified in a file field:

MyApp.Views.file = Ember.View.extend                             
  tagName: 'input'                                     
  attributeBindings: ['type', 'id']                     
  type: 'file' 
                           
  change: (e)->       
    view = this                                
    reader = new FileReader()                                         
    reader.onload = (e)->             
      view.set('file', e.target.result)                    
    reader.readAsText(e.target.files[0]) 

This can then be invoked in a template as follows:

{{view MyApp.Views.file fileBinding="SomeModel.attribute" }}

I expect this approach to be unsuitable for extremely large files as it will read the entire file into memory and transmit it as part of the payload rather than as a file upload, for some value of extremely large...

No comments:

Post a Comment