我正在寻找一种使用谷歌网络工具包进行文件上传的方法,带有自定义进度条。我不是在寻找显示自己的进度条的插件,而是在寻找可以调用我的回调方法并通知它进度的东西,所以我可以显示自己的进度条。
如果这不可能,那么我想知道如何访问 HTML5 文件 API,以便我可以构建自己的文件上传器小部件。
有任何想法吗?
谢谢。
GWT 中有很多问题很难解决:
FormData
对象,所以必须使用 JSNI 来获取。RequestBuilder
不支持发送FormaData
,只支持字符串。RequestBuilder
不支持上传或下载进度通知。FileUpload
不支持多属性。幸运的是,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 code 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 支持这一点时,您不必修改代码中的任何内容。
所有构建块都在Elemental中,但可能无法在任何地方工作(Elemental “接近金属”,没有任何支持检测或隐藏/解决浏览器错误/差异)。
或者你可以使用 JSNI。