HTML5 and Javascript : Opening and Reading a Local File with File API
Asked Answered
B

2

1

I am using Google Web Toolkit for a project and would like the user to select a text file to open in a text window inside the browser. Here's the almost working code:

 private DialogBox createUploadBox() {
     final DialogBox uploadBox = new DialogBox();
     VerticalPanel vpanel = new VerticalPanel();
     String title = "Select a .gms file to open:";
     final FileUpload upload = new FileUpload();
     uploadBox.setText(title);
     uploadBox.setWidget(vpanel);
     HorizontalPanel buttons = new HorizontalPanel();
     HorizontalPanel errorPane = new HorizontalPanel();
     Button openButton = new Button( "Open", new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            String filename = upload.getFilename();
            int len = filename.length();
            if (len < 5) {
                Window.alert("Please enter a valid filename.\n\tFormat: <filename>.gms");
            } else if (!filename.substring(len-4).toLowerCase().equals(".gms")) {
                Window.alert(filename.substring(len-4) + " is not valid.\n\tOnly files of type .gms are allowed.");
            } else {
                Window.alert(getFileText(filename));
            }
        }
        private native String getFileText(String filename) /*-{
            // Check for the various File API support.
            if (window.File && window.FileReader && window.FileList && window.Blob) {
                // Great success! All the File APIs are supported.
                var reader = new FileReader();
                var file = File(filename);
                str = reader.readAsText(file);
                return str;
            } else {
                alert('The File APIs are not fully supported in this browser.');
                return;
            }
        }-*/;
     });
     Button cancelButton = new Button( "Cancel", 
             new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            uploadBox.hide();               
        }
     });
     buttons.add(openButton);
     buttons.add(cancelButton);
     vpanel.add(upload);
     vpanel.add(buttons);
     vpanel.add(errorPane);
     uploadBox.setAnimationEnabled(true);
     uploadBox.setGlassEnabled(true);
     uploadBox.center();
     return uploadBox;
 }

Whenever I try to actually use this function in my program, I get:

(NS_ERROR_DOM_SECURITY_ERR): Security error

I'm certain it is being cased by:

var file = new File(filename, null);

Disclaimer: I'm not a Javascript programmer by any stretch, please feel free to point out any obvious mistakes I'm making here.

Bobby answered 12/4, 2012 at 21:19 Comment(1)
re: the edits - window/$wnd is probably the only point that is gwt-specific. That, and how to pass in the InputElement instance.Glabella
G
3

Instead of using window, you should almost always use $wnd. See https://developers.google.com/web-toolkit/doc/latest/DevGuideCodingBasicsJSNI#writing for more details about JSNI.

It could also be worthwhile to add a debugger statement while using something like Firebug, or Chrome's Inspector. This statement will stop the JS code in the debugger as if you had put a breakpoint there, are allow you to debug in Javascript, stepping one line at a time to see exactly what went wrong.

And finally, are you sure the file you are reading is permitted by the browser? From http://dev.w3.org/2006/webapi/FileAPI/#dfn-SecurityError, that error could be occurring because the browser has not been permitted access to the file. Instead of passing in the String, you might pass in the <input type='file' /> the user is interacting with, and get the file they selected from there.


Update (sorry for the delay, apparently the earlier update I made got thrown away, took me a bit to rewrite it):

Couple of bad assumptions being made in the original code. Most of my reading is from http://www.html5rocks.com/en/tutorials/file/dndfiles/, plus a bit of experimenting.

  • First, that you can get a real path from the <input type='file' /> field, coupled with
  • that you can read arbitrary files from the user file system just by path, and finally
  • that the FileReader API is synchronous.

For security reasons, most browsers do not give real paths when you read the filename - check the string you get from upload.getFilename() in several browsers to see what it gives - not enough to load the file. Second issue is also a security thing - very little good can come of allowing reading from the filesystem just using a string to specify the file to read.

For these first two reasons, you instead need to ask the input for the files it is working on. Browsers that support the FileReader API allow access to this by reading the files property of the input element. Two easy ways to get this - working with the NativeElement.getEventTarget() in jsni, or just working with FileUpload.getElement(). Keep in mind that this files property holds multiple items by default, so in a case like yours, just read the zeroth element.

private native void loadContents(NativeEvent evt) /*-{
    if ($wnd.File && $wnd.FileReader && $wnd.FileList && $wnd.Blob) {
        // Great success! All the File APIs are supported.
        var reader = new FileReader();
        reader.readAsText(evt.target.files[0]);
//...

or

private native void loadContents(Element elt) /*-{
    if ($wnd.File && $wnd.FileReader && $wnd.FileList && $wnd.Blob) {
        // Great success! All the File APIs are supported.
        var reader = new FileReader();
        reader.readAsText(elt.files[0]);
//...

For the final piece, the FileReader api is asynchronous - you don't get the full contents of the file right away, but need to wait until the onloadend callback is invoked (again, from http://www.html5rocks.com/en/tutorials/file/dndfiles/). These files can be big enough that you wouldn't want the app to block while it reads, so apparently the spec assumes this as the default.

This is why I ended up making a new void loadContents methods, instead of keeping the code in your onClick method - this method is invoked when the field's ChangeEvent goes off, to start reading in the file, though this could be written some other way.

// fields to hold current state
private String fileName;
private String contents;
public void setContents(String contents) {
  this.contents = contents;
}

// helper method to read contents asynchronously 
private native void loadContents(NativeEvent evt) /*-{;
    if ($wnd.File && $wnd.FileReader && $wnd.FileList && $wnd.Blob) {
        var that = this;
        // Great success! All the File APIs are supported.
        var reader = new FileReader();
        reader.readAsText(evt.target.files[0]);
        reader.onloadend = function(event) {
            [email protected]::setContents(Ljava/lang/String;)(event.target.result);
        };
    } else {
        $wnd.alert('The File APIs are not fully supported in this browser.');
    }
}-*/;

// original createUploadBox
private DialogBox createUploadBox() {
  final DialogBox uploadBox = new DialogBox();
  VerticalPanel vpanel = new VerticalPanel();
  String title = "Select a .gms file to open:";
  final FileUpload upload = new FileUpload();
  upload.addChangeHandler(new ChangeHandler() {
    @Override
    public void onChange(ChangeEvent event) {
      loadContents(event.getNativeEvent());
      fileName = upload.getFilename();
    }
  });
  // continue setup

The 'Ok' button then reads from the fields. It would probably be wise to check that contents is non null in the ClickHandler, and perhaps even null it out when the FileUpload's ChangeEvent goes off.

Glabella answered 12/4, 2012 at 22:22 Comment(7)
Sorry, but like I said before, I'm not a javascript programmer. Could you give a concrete example of using that <input type='file'/> bit?Bobby
I think you are correct about the browser not allowing access to the file. Do I need to submit the file in a form?Bobby
Not submit, but let the user browse to a file, then look at their selection. Take a look at html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files - you'll add a handler for ChangeEvent to the FileUpload widget - user clicks browse, selects something, and you'll be able to read the NativeEvent out like they do in handleFileSelect. You might need a custom widget other than FileUpload, its been a while since I played with this. Update the Q with an almost-working code sample, and I'll see if I can follow up more.Glabella
Colin - what you are saying kind of makes sense to me. I'm missing some fundamentals, definitely. I've updated my question with the entire code block. Thanks for the help.Bobby
Just put an update with a mostly working impl, let me know if you have any q's.Glabella
One question: why the var that = this; reassignment? I can think of one reason myself, but I just want to hear it from someone who knows what they are doing :)Bobby
The that=this is for the onloadend callback - this isn't really the same in JS as it is in Java, so you need to account for the fact that in that callback, this will mean whatever the function is being invoked on. A quick example suggests it will the the FileReader, but in many cases callbacks are invoked with window (in gwt, $wnd) as the this.Glabella
H
0

As far as I can see you can only use new File(name) when writing extensions: https://developer.mozilla.org/en/Extensions/Using_the_DOM_File_API_in_chrome_code

Handbreadth answered 12/4, 2012 at 22:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.