用于 GWT 的 Moxieapps 文件上传器添加了多个上传按钮

Moxieapps file uploader for GWT adding multiple upload buttons

我正在构建的 GWT 网络应用程序有一个页面,用户可以在其中上传 CSV 文件。上传代码使用 Moxieapps GWT Uploader,效果很好。

但是,我发现了一个奇怪的场景,离开该页面并返回该页面会再次添加上传按钮。所以我第三次访问该页面时,上传部分将如下所示:

并且在检查器中查看生成的 HTML 的相关部分显示 input 和包含 "button" 的 div 被一遍又一遍地添加(尽管只有一个空降区):

我检查了我的代码很多次,看看我是否正在做一些可能导致此问题的事情,但没有找到任何东西。您实际上并没有手动添加按钮或输入;这是由框架自动完成的。 fileUploader 仅初始化一次(这是 GWT 客户端代码,我已经使用检查器进行了调试,并将日志语句记录到控制台以确认这一点):

fileUploader.setButtonDisabled(true).setFileTypes("*.csv")
    .setUploadURL(getBaseUrl() + "/fileUpload.upload")
    .setButtonText("<span class=\"buttonText\">Select CSV file to upload</span>")
    .setFileSizeLimit(FILE_SIZE_LIMIT)
    .setButtonCursor(CustomUploader.Cursor.HAND)
    .setButtonAction(CustomUploader.ButtonAction.SELECT_FILE)
    .setUploadProgressHandler(new UploadProgressHandler() {...})
    .setUploadSuccessHandler(...)
    // etc. with other handlers

从其他几个地方调用了方法 setButtonText(),并且文本发生了应有的变化,但仅在最后一个按钮(如果有多个按钮)上发生变化。否则,据我所知,我的代码中没有任何内容可以添加按钮。

还有其他人遇到过这个问题吗?我需要设置一些 属性 来防止这种情况发生吗?这可能是 moxieapps 代码中的错误吗?

写完我的问题,在最后加上"Could it be a bug in the moxieapps code?",我跟进了那个怀疑,结果确实是org.moxieapps.gwt.uploader.client.Uploader class.

input 和 "select file" 按钮被添加到那个 class 的 onLoad() 方法中,没有检查它们是否已经被添加。

看起来这个框架已经有一段时间没有任何积极的开发了,所以我认为是时候使用自定义覆盖版本了。我已经对此进行了测试并且有效:

package yourpackagename.client.override;

import java.util.Iterator;

import org.moxieapps.gwt.uploader.client.Uploader;

import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.WidgetCollection;

/**
 * The sole reason this class exists is to fix a bug in the moxieapps uploader
 * (org.moxieapps.gwt.uploader-1.1.0.jar) where it adds a new upload input and
 * button each time its <code>onLoad()</code> method is called, i.e. every time
 * you navigate away from the page and then back to it.
 */
public class CustomUploader extends Uploader {
    @Override
    protected void onLoad() {
        boolean hasFileUploadAlready = false;
        WidgetCollection children = getChildren();
        for (Iterator<Widget> iterator = children.iterator(); iterator.hasNext();) {
            Widget eachWidget = iterator.next();
            if (eachWidget instanceof FileUpload) {
                hasFileUploadAlready = true;
            }
        }
        // Only call the super method if there isn't already a file upload input and button
        if (!hasFileUploadAlready) {
            super.onLoad();
        }
    }
}

我没有引用 org.moxieapps.gwt.uploader.client.Uploader,而是将引用更改为指向我的自定义上传器 class,它现在将检查现有的 FileUpload 子窗口小部件,并且只需如果找到这样的小部件,请跳过原始 onLoad() 代码。

可能有点撬棍方法,但它有效(在我的例子中,更改 maven 管理的 JAR 文件不是很实用)。希望这对遇到此问题的其他人有用。