Upload file to hidden input using protractor and s

2019-02-24 14:14发布

I've got a hidden file input field like this:

<input type="file" id="fileToUpload-1827" multiple="" onchange="angular.element(this).scope().setFiles(this)" data-upload-id="1827" class="hidden-uploader">

I'd like to be able to upload files to this. The normal way to do this in protractor would be to do:

ptor.findElement(protractor.By.css('.file-upload-form input')).sendKeys('/path/to/file')

But because the input element isn't visible, I get an error.

I tried:

  ptor.driver.executeScript("return $('.file-upload-form input')[0].removeClass('hidden-uploader');").then(function () {
    ptor.findElement(protractor.By.css('.file-upload-form input')).sendKeys('hello');
  })

But got the error

UnknownError: $(...)[0].removeClass is not a function

It seems ridiculous to have to use executeScript to make an element visible so that I can upload a file, is there a better way? If not, how do I unhide the element?

The full html for the input form is:

<form class="file-upload-form ng-scope ng-pristine ng-valid" ng-if="ajaxUploadSupported">
<strong>Drag files here to upload</strong> or

<label for="fileToUpload-1953">
  <div class="btn btn-info select-file-btn">
    Click to Select
  </div>
</label>

<div>
      <input type="file" id="fileToUpload-1953" multiple="" onchange="angular.element(this).scope().setFiles(this)" data-upload-id="1953" class="hidden-uploader">
</div>
</form>

2条回答
你好瞎i
2楼-- · 2019-02-24 14:49

The only way I could find to do this in the end was to use javascript to make the input element visible.

So I have a function unhideFileInputs:

  var unhideFileInputs = function () {
    var makeInputVisible = function () {
      $('input[type="file"]').removeClass('hidden-uploader');
    };

    ptor.driver.executeScript(makeInputVisible);
  }

This contains the function 'makeInputVisible' which is executed in the browser when I call ptor.driver.executeScript(makeInputVisible). Because I know my page contains jQuery I can use the jQuery removeClass method to unhide my file input element.

To see more on how to execute javascript in the browser using webdriver, see the answer to this question (although the answer uses executeAsyncScript rather than executeScript).

查看更多
Lonely孤独者°
3楼-- · 2019-02-24 14:58

To add on user2355213s answer for the more current releases of protractor. ptor is obsolote and instead browser should be used. Also, executeScript() expects a string as parameter. So I ended up using

browser.executeScript('$(\'input[type="file"]\').attr("style", "");');

as my visibility setting was directly applied to the element. Of course, you can also use

browser.executeScript('$(\'input[type="file"]\').removeClass("hidden-uploader");');

depending on your HTML/CSS.

查看更多
登录 后发表回答