我如何在Selenium表单上上传文件

时间:2019-04-03 05:42:59

标签: java selenium

    <form method="post" enctype="multipart/form-data" class="box dropzone dz-clickable" action="/upload" id="drop">
     <div class="disable-click" style="display: none;">
     <a class="cross" href="javascript:void(0)">
     <img style="cursor:pointer;" src="http://demopayrollplus.finpay.pk/public/assets/images/cross-icon.png" alt="Remove File" title="Remove File"></a>
      </div>
      <div class="box__input dz-message">
           <img id="uploadIcon" src="http://demopayrollplus.finpay.pk/public/assets/images/upload-icon.svg">
           <label class="uploadedFileName">Drop your file here</label>
      </div>
 </form>

我尝试了以下方法

  1. 网络元素。
  2. 动作
  3. 发送密钥

但是没有任何作用却说这不是难处理的元素

WebElement ele = driver.findElement(By.id("drop"));
ele.sendkeys("file path");

2 个答案:

答案 0 :(得分:3)

对于拖放文件上传类型,可以使用下面提到的代码。这段代码会将文件从您提到的位置拖放到文件上传位置。

ChromeDriver driver = new ChromeDriver();

driver.get("URL");

// locate the drop area
WebElement droparea = driver.findElement("file upload element");
Point point = droparea.getLocation();
        int xcord = point.getX();
        int ycord = point.getY();
// drop the file
DropFile(new File("location of file to be uploaded"), droparea, xcord ,ycord);


public static void DropFile(File filePath, WebElement target, int offsetX, int offsetY) {
        if(!filePath.exists())
            throw new WebDriverException("File not found: " + filePath.toString());

        WebDriver driver = ((RemoteWebElement)target).getWrappedDriver();
        JavascriptExecutor jse = (JavascriptExecutor)driver;
        WebDriverWait wait = new WebDriverWait(driver, 30);

        String JS_DROP_FILE =
            "var target = arguments[0]," +
            "    offsetX = arguments[1]," +
            "    offsetY = arguments[2]," +
            "    document = target.ownerDocument || document," +
            "    window = document.defaultView || window;" +
            "" +
            "var input = document.createElement('INPUT');" +
            "input.type = 'file';" +
            "input.style.display = 'none';" +
            "input.onchange = function () {" +
            "  var rect = target.getBoundingClientRect()," +
            "      x = rect.left + (offsetX || (rect.width >> 1))," +
            "      y = rect.top + (offsetY || (rect.height >> 1))," +
            "      dataTransfer = { files: this.files };" +
            "" +
            "  ['dragenter', 'dragover', 'drop'].forEach(function (name) {" +
            "    var evt = document.createEvent('MouseEvent');" +
            "    evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);" +
            "    evt.dataTransfer = dataTransfer;" +
            "    target.dispatchEvent(evt);" +
            "  });" +
            "" +
            "  setTimeout(function () { document.body.removeChild(input); }, 25);" +
            "};" +
            "document.body.appendChild(input);" +
            "return input;";

        WebElement input =  (WebElement)jse.executeScript(JS_DROP_FILE, target, offsetX, offsetY);
        input.sendKeys(filePath.getAbsoluteFile().toString());
        wait.until(ExpectedConditions.stalenessOf(input));
    }

答案 1 :(得分:0)

点击文件上传按钮后,使用此方法上传文件

 public void fileUploadUsingRobot(String filePath) {
            try{
            Robot robot= new Robot();
            StringSelection ss = new StringSelection(filePath);
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
            robot.delay(3000);

            robot.keyPress(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_V);

            robot.keyRelease(KeyEvent.VK_V);
            robot.keyRelease(KeyEvent.VK_CONTROL);
            robot.delay(3000);
            robot.keyPress(KeyEvent.VK_ENTER);
            robot.keyRelease(KeyEvent.VK_ENTER);
            robot.delay(3000);

            }
            catch(Exception e) {
                log.error(e);
            }
        }

Action类只能处理拖放操作,如果您使用的是基于窗口的文件上传,请使用上述方法