2

Trying to upload a file with a HTML input element via Selenium/ChromeDriver.

If the file is a local file everything is OK.

But I need to upload from a URL. In that case the driver throws an error.

If I upload the URL with chrome manually (click on "Select file" and paste the URL as filename and click OK) the upload works as expected.

HTML:

<input type="file" name="file1">

C# code:

var driver = new ChromeDriver();
driver.Navigate().GoToUrl("<URL HERE>");
var input = driver.FindElement(By.Name(name));
ele.SendKeys("C:\\pic.png"); //works because local file exists
ele.SendKeys("https://wikipedia.org/static/favicon/wikipedia.ico"); //fails

Exception: OpenQA.Selenium.WebDriverException: "invalid argument: File not found : https://wikipedia.org/static/favicon/wikipedia.ico (Session info: chrome=92.0.4515.131)"

I found out that the exception is thrown because the drivers DefaultFileDetector cant resolve it to a file.

So I tried to implement my own FileDetector and assign it to the driver:

var allowsDetection = driver as IAllowsFileDetection;
if (allowsDetection != null)
{
   allowsDetection.FileDetector = new DummyFileDetector();
}

DummyFileDetector:

class DummyFileDetector : IFileDetector
{

    public bool IsFile(string keySequence)
    {
        return true;
    }
}

But DummyFileDetector.IsFile is never called (it seems that allowsDetection.FileDetector = new DummyFileDetector() does not change the FileDetector of the driver).

I don't want to download the file and then upload it (if that is possible). As said manually set the URL in the file selection dialog does the trick, but not with Selenium.

Any ideas?

Boardwish
  • 495
  • 3
  • 16

2 Answers2

1

I searched many questions here and on other internet resources, and found that the only way to upload a file from external URL with driver.SendKeys() method is first to download it to your local disk and then upload with driver.SendKeys()
Proof

Prophet
  • 32,350
  • 22
  • 54
  • 79
0

I've never used C# before, but I think a really simple way to go around this is downloading the file, reuploading it, then deleting it. I'm sure you can do it in C#. I understand in selenium python it is pretty simple to do that, I don't think python code would be helpful here though (lol)

Simon Nasser
  • 112
  • 12
  • Yes, that is now the solution/workaround because there is no other way. But as I said it would be nice if URLs are accepted. – Boardwish Aug 05 '21 at 10:37