HTML5和Javascript:使用File API打开和读取本地文件 [英] HTML5 and Javascript : Opening and Reading a Local File with File API

查看:177
本文介绍了HTML5和Javascript:使用File API打开和读取本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google Web Toolkit进行项目,并希望用户选择要在浏览器内的文本窗口中打开的文本文件。这是几乎正常工作的代码:

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):安全错误

我确定它正在装箱by:

I'm certain it is being cased by:

var file = new File(filename, null);

免责声明:我不是任何一个Javascript程序员,请随时指出任何明显的我在这里犯的错误。

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

推荐答案

而不是使用窗口,你应该几乎总是使用 $ wnd 。请参阅 https://developers.google.com/web-toolkit/doc/最新/ DevGuideCodingBasicsJSNI#writing 有关JSNI的更多详细信息。

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.

添加调试器使用Firebug或Chrome的Inspector之类的声明。这句话将停止调试器中的JS代码,就好像你在那里放了一个断点一样,允许你在Javascript中调试,一次踩一行就能看出到底出了什么问题。

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.

最后,您确定浏览器允许您正在阅读的文件吗?来自 http://dev.w3.org/2006/webapi/FileAPI/# dfn-SecurityError ,可能发生该错误,因为浏览器未被允许访问该文件。您可以传入用户正在与之交互的< input type ='file'/> ,而不是传入String,并从中获取他们选择的文件。

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):

在原始代码中做出了一些错误的假设。我的大部分阅读都来自 http://www.html5rocks.com/en/tutorials/ file / dndfiles / ,再加上一些实验。

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.


  • 首先,你可以从<$获得真实路径c $ c>< input type ='file'/> 字段,再加上

  • 您可以从用户文件系统中读取任意文件路径,最后

  • FileReader API是同步的。

  • 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.

出于安全考虑,大多数浏览器在读取文件名时都没有提供真实的路径 - 检查从<$ c $获得的字符串c> upload.getFilename()在几个浏览器中查看它给出的内容 - 不足以加载文件。第二个问题也是一个安全问题 - 允许从文件系统中读取只是使用字符串来指定要读取的文件的好处。

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.

出于前两个原因,你需要向输入询问它正在处理的文件。支持FileReader API的浏览器允许通过读取input元素的 files 属性来访问它。有两种简单的方法 - 在jsni中使用NativeElement.getEventTarget(),或者只使用FileUpload.getElement()。请记住,这个文件属性默认包含多个项目,所以在像你这样的情况下,只需读取第0个元素。

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]);
//...

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]);
//...

对于最后一块, FileReader api是异步的 - 你没有立即得到文件的全部内容,但需要等到调用 onloadend 回调(再次,来自 http://www.html5rocks.com/en/tutorials/file/dndfiles / )。这些文件可能足够大,以至于您不希望应用程序在读取时阻止,因此显然规范将此视为默认值。

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.

这就是我结束的原因制作新的 void loadContents 方法,而不是将代码保存在 onClick 方法中 - 此方法在调用时调用字段的 ChangeEvent 关闭,开始读取文件,虽然这可以用其他方式编写。

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

确定按钮然后从字段中读取。在 ClickHandler 中检查内容是否为空可能是明智的,甚至可能在 FileUpload 's ChangeEvent 熄灭。

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.

这篇关于HTML5和Javascript:使用File API打开和读取本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆