HTML5 and Javascript : Opening and Reading a Local File with File API

一曲冷凌霜 提交于 2019-12-04 19:43:10

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) {
            that.@com.sencha.gxt.examples.test.client.Test::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.

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

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