GWT中存在许多问题,因此很难解决:
FormData
GWT中没有对象,因此您必须使用JSNI来获得对象。RequestBuilder
不支持发送FormaData
,仅支持字符串。RequestBuilder
不支持上传或下载进度通知。FileUpload
不支持多属性。- GWT中的Elemental包仅适用于Webkit浏览器,并且上次尝试使用File Api时遇到了一些问题。
幸运的是,gwtquery 1.0.0具有许多有助于解决问题的功能。
在这里,您有一个有效的示例(只有很少的代码行),该示例在所有支持HTML5文件api的浏览器中均可使用:
import static com.google.gwt.query.client.GQuery.*;[...]final FileUpload fileUpload = new FileUpload();RootPanel.get().add(fileUpload);$(fileUpload) // FileUpload does not have a way to set the multiple attribute, // we use gQuery instead .prop("multiple", true) // We use gQuery events mechanism .on("change", new Function() { public void f() { // Use gQuery utils to create a FormData object instead of JSNI JavascriptObject form = JsUtils.runJavascriptFunction(window, "eval", "new FormData()"); // Get an array with the files selected JsArray<JavascriptObject> files = $(fileUpload).prop("files"); // Add each file to the FormData for (int i = 0, l = files.length(); i < l; i++) { JsUtils.runJavascriptFunction(form, "append", "file-" + i, files.get(i)); } // Use gQuery ajax instead of RequestBuilder because it // supports FormData and progress Ajax.ajax(Ajax.createSettings() .setUrl(url) .setData((Properties)form)) // gQuery ajax returns a promise, making the pre more declarative .progress(new Function() { public void f() { double total = arguments(0); double done = arguments(1); double percent = arguments(2); // Here you can update your progress bar console.log("Uploaded " + done + "/" + total + " (" + percent + "%)"); } }) .done(new Function() { public void f() { console.log("Files uploaded, server response is: " + arguments(0)); } }) .fail(new Function() { public void f() { console.log("Something went wrong: " + arguments(0)); } }); }});另一个选择是使用gwtupload,它支持任何浏览器,并且带有一些不错的小部件和进度条,即使您可以插入自己的进度和状态小部件。
它尚未使用HTML5 File
api,而是基于服务器侦听器的ajax解决方案。不过,它将在将来的版本中支持html5,并回退到旧浏览器的ajax机制。当gwtupload支持此功能时,您无需修改代码中的任何内容。



