使用FormData进行GWT文件上传的方法是什么?

时间:2017-04-16 21:02:21

标签: java jquery gwt

我有这个上传图像(文件)的工作代码,我想把它转换为纯GWT(没有JSNI):

Element element = DOM.createElement("input");
element.setAttribute("type", "file");
element.setAttribute("accept", "image/*");
JSNI.ajaxUpload(element, SERVER_URL + "/files",
        APP_ID,
        REST_API_KEY,
        new AsyncCallback<String>() {
            @Override
            public void onFailure(Throwable throwable) {
                Browser.getWindow().getConsole().log("Unable to upload");
            }
            @Override
            public void onSuccess(String s) {
                Browser.getWindow().getConsole().log("Uploaded " + s);
                JSONObject jsonObject = JSONParser.parseStrict(s).isObject();
            }
        });
JSNI.click(element);

ajaxUpload函数是这样的:

   public static native void ajaxUpload(Element upload,
                                         String uploadUrl,
                                         String applicationId,
                                         String restApiKey,
                                         AsyncCallback<String> callback)/*-{
        var file;
        $wnd.$(upload).unbind();
        $wnd.$(upload).bind("change", function(e) {
            var files = e.target.files || e.dataTransfer.files;
            file = files[0];
            console.log('File: ' + file);
            var serverUrl = uploadUrl + '/' + file.name;
            console.log(file);
            $wnd.$.ajax({
                type: "POST",
                beforeSend: function(request) {
                    request.setRequestHeader("X-Parse-Application-Id", applicationId);
                    request.setRequestHeader("X-Parse-REST-API-Key", restApiKey);
                    request.setRequestHeader("Content-Type", file.type);
                },
                url: serverUrl,
                data: file,
                processData: false,
                contentType: false,
                success: function(data) {
                    callback.@com.google.gwt.user.client.rpc.AsyncCallback::onSuccess(*)(JSON.stringify(data));
                    //alert("File available at: " + data.url);
                },
                error: function(data) {
                    var obj = $wnd.jQuery.parseJSON(data);
                    //alert(obj.error);
                    // TODO
                    callback.@com.google.gwt.user.client.rpc.AsyncCallback::onSuccess(*)(JSON.stringify(data));
                }
            });
        });
    }-*/;
I have tried this and would not work on the same server which the above code works:
    Element element = DOM.createElement("input");
    element.setAttribute("type", "file");
    element.setAttribute("accept", "image/*");
    $(element).unbind("change");
    $(element).bind("change", new Function() {
        @Override
        public boolean f(Event e) {
            FileObject file = (FileObject) getFile(e);
            Browser.getWindow().getConsole().log("filename=" + file.getName());
            FormData formData = FormData.create();
            formData.append("file", file);
            XMLHTTPRequest2 xhr = (XMLHTTPRequest2) XMLHTTPRequest2.create();
            xhr.open("POST", Bootstrap.SERVER_URL + "/files/" + file.getName());
            xhr.setOnReadyStateChange(new ReadyStateChangeHandler() {
                public void onReadyStateChange(XMLHttpRequest xhr) {
                    String result = xhr.getResponseText();
                    Browser.getWindow().getConsole().log("Result=" + result);
                }
            });
            xhr.setRequestHeader("X-Parse-Application-Id", Bootstrap.APP_ID);
            xhr.setRequestHeader("X-Parse-REST-API-Key", Bootstrap.REST_API_KEY);
            xhr.setRequestHeader("Content-Type", file.getType());
            xhr.send(formData);
            return true;
        }
    });
    JSNI.click(element); 
  

甚至我提出的GwtQuery(GQuery)解决方案也没有   工作:

        final FileUpload fileUpload = new FileUpload();
        $(fileUpload)
                .prop("multiple", true)
                .on("change", new Function() {
                    public void f() {
                        FormData form = FormData.create();
                        JsArray<JavaScriptObject> files =  $(fileUpload).prop("files");
                        FileObject fileObject = (FileObject) files.get(files.length() - 1);
                        JsUtils.runJavascriptFunction(form, "append", "file", fileObject);
                        Ajax.ajax(Ajax.createSettings()
                                .setUrl(Bootstrap.SERVER_URL + "/files/" + fileObject.getName())
                                .setData((Properties)(JavaScriptObject)form))
                                .progress(new Function() {
                                    public void f() {
                                        double total = arguments(0);
                                        double done = arguments(1);
                                        double percent = arguments(2);
                                        Browser.getWindow().getConsole().log("Uploaded " + done + "/" + total + " (" + percent + "%)");
                                    }
                                })
                                .done(new Function() {
                                    public void f() {
                                        Browser.getWindow().getConsole().log("Files uploaded, server response is: " + arguments(0));
                                    }
                                })
                                .fail(new Function() {
                                    public void f() {
                                        Browser.getWindow().getConsole().log("Something went wrong: " + arguments(0));
                                    }
                                });
                    }
                });
        fileUpload.click();

FileObject.java

public class FileObject extends JavaScriptObject {
    protected FileObject() {}
    public final native String getName() /*-{
        return this.name;
    }-*/;
    public final native String getType() /*-{
        return this.type;
    }-*/;
}

FormData.java

public class FormData extends JavaScriptObject {
    //default constructor
    //see more at http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#formdata
    protected FormData() {
    }
    /**
     * add a pair of value to form.
     * <p>
     * See <a href="http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#formdata"
     * >http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#formdata</a>.
     *
     * @param name the name to be add
     * @param value the value to be add
     */
    public final native void append(String name, String value) /*-{
        this.append(name, value);
    }-*/;

    public final native void append(String name, JavaScriptObject value) /*-{
        this.append(name, value);
    }-*/;
    /**
     * Creates an XMLHttpRequest object.
     *
     * @return the created object
     */
    public static native FormData create() /*-{
        return new FormData();
    }-*/;
}

如何将此文件上传到用户JSNI / jQuery?

0 个答案:

没有答案