Programmatically upload / add file via Dropzone e.

2019-07-11 13:38发布

I am writing a Selenium test case where one of the steps is to upload a file via Dropzone.js.

(As Selenium can run Javascript in the browser, so if it can be done programmatically in Javascript that would be fine too.)

I want to avoid going all the way to simulate opening the file browser window, selecting file etc, as that goes outside of what the web driver can handle and gets very complicated. In pseudo code, I'd like to do something like this:

1. Select some Dropzone element 2. Set file path 3. Submit (upload the file)

There is one likely approach mentioned in an existing question (Unable to upload file using python selenium webdriver on http://www.dropzonejs.com), which uses the "dz-hidden-input" element (a DOM file input).

Unfortunately it does not work (at least not in the current version of Dropzone) - after setting the file to the element, the Dropzone .files is still empty and no upload takes place.

After looking in the Dropzone source, I came up with a working solution by extending the above:

1. Set file path in the "dz-hidden-input" element 2. Use javascript to retrieve the File object from the element 3. Pass the file to dropzone.addFile(file)

But my concern is it is really a hack, as both the hidden-input and .addFile are not documented, and the test will break in the future if Dropzone changes implementation etc.

Is there any better / documented way to do this?

(To clarify - I am trying to upload a new file, not to show an existing file as mentioned in the Dropzone FAQ)

1条回答
再贱就再见
2楼-- · 2019-07-11 14:18

Click to Input button -> Use web driver clipboard/java robot -> Paste/type file location + file name > Hit robot enter.

final String fileName = "textfile.txt";
final String filePath = "\\data\\public\\other\\" + fileName;
zUploadFile (filePath );

public void zUploadFile (String filePath) throws HarnessException {

    // Put path to your image in a clipboard
    StringSelection ss = new StringSelection(filePath);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
    // OR use java robot for entire filepath
    Thread.sleep(10000);

    // Imitate mouse events like ENTER, CTRL+C, CTRL+V
    Robot robot;
    try {
        robot = new Robot();
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);

    } catch (AWTException e) {
        e.printStackTrace();
    }
}
查看更多
登录 后发表回答