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.
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
来源:https://stackoverflow.com/questions/10132018/html5-and-javascript-opening-and-reading-a-local-file-with-file-api