Protractor image upload doesn't work on IE and

2019-06-05 23:27发布

问题:

I am trying to upload image on the input type:file control using protractor.

I am using the below code:

var basePath='../testdata/testappicons/accepted';
var randomIcon=randomIntFromInterval(1,6);
var overallPathToIcon=basePath+randomIcon+'.png';
var fileToUpload = overallPathToIcon;
console.log(fileToUpload);
var absolutePath = path.resolve(__dirname, fileToUpload)
browser.executeScript('$(\'input[type="file"]\').attr("style", "");');
$('input[type="file"]').sendKeys(absolutePath); 

The above code works well on the chrome and I am able to upload files but when I use the same code on firefox and IE. I get the following error:

ElementNotVisibleError: Element is not displayed

This is the HTML for the form:

div class="fileUpload" ng-click="IsInValid=true">
<label class="btn btn-white uploadBtn" title="Upload image file" for="upload-image">
<input id="uploadFile" type="text" readonly="" placeholder="Browse new app icon" value="maxsizepngfile.png">
<input id="upload-image" class="upload ng-pristine ng-untouched ng-valid ng-isolate-scope" type="file" ng-model="image" image="appicon" accept="image/*">
</label>
<label class="btn btn-warning" for="upload-image">
<span>Browse</span>
</label>
</div>

My guess is this since it is a read only this is why it isn't working. Can anyone please help me out on this?

This is the code that got working for me

var basePath='../testdata/testappicons/accepted';
        var randomIcon=randomIntFromInterval(1,6);
      var overallPathToIcon=basePath+randomIcon+'.png';
          var fileToUpload = overallPathToIcon;
          console.log(fileToUpload);
      var absolutePath = path.resolve(__dirname, fileToUpload)
      //browser.executeScript('$(\'input[type="file"]\').attr("style", "");');

        var elm = $('input[type="file"]');  // protractor's shortcut to element(by.css("css"))
        //browser.executeScript('var input = $("input:file"); var elm = input[0];elm.style.visibility = "visible"; elm.style.height = "1px"; elm.style.width = "1px";elm.style.opacity = 1;');

        browser.executeScript('var input = $("input:file"); input[0].removeAttribute("class");');
        elm.sendKeys(absolutePath);

回答1:

It would still be a guess, but an educated one: do not involve jQuery in setting the style:

var elm = $('input[type="file"]');  // protractor's shortcut to element(by.css("css"))
browser.executeScript('arguments[0].style = {};', elm.getWebElement());

elm.sendKeys(absolutePath);

Also, to follow the @dmitankin's comment and the Does WebDriver support file uploads? FAQ section, try making the element visible this way:

function makeVisible(arguments) {
    var elm = arguments[0];

    elm.style.visibility = 'visible'; 
    elm.style.height = '1px'; 
    elm.style.width = '1px';
    elm.style.opacity = 1;
}
browser.executeScript(makeVisible, elm.getWebElement());