'invalid argument: File not found error when trying to upload a file

I have an E2E test to upload a file to the application which works on my local machine but fails to run on Browserstack. But fails with reason :

invalid argument: File not found : /home/travis/build/xx/xx/e2e/src/xx/testfile

Here is the code

let fileToUpload = 'testfile';
let absolutePath = path.resolve(__dirname, fileToUpload);
await browser.setFileDetector(new remote.FileDetector());
let fileElem = $('input[type="file"]');
await fileElem.sendKeys(absolutePath);

I have the files upload in my code base for travis to pick them. Any inputs are appreciated.

Thanks



Solution 1:[1]

Since the file upload is working from your local machine, you can try using the Local File Detector Option.

driver.setFileDetector(new LocalFileDetector());
driver.get("http://www.fileconvoy.com/");
driver.findElement(By.id("upfile_0")).sendKeys("C:\\Users\\hello\\url.txt");
driver.findElement(By.id("readTermsOfUse")).click();
driver.findElement(By.name("form_upload")).submit();

The above code snippet will upload a file located on the local machine. The same details are available here: https://www.browserstack.com/automate/java#enhancements-uploads-downloads

You can port this in the language of your choice.

Solution 2:[2]

 ((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector());
 driver.get("https://www.monsterindia.com/seeker/registration");                 

 WebElement browser = driver.findElement(By.xpath("//*[@id=\"file-upload\"]"));                  
     //Upload button xpath
                        
   browser.sendKeys("add here upload file path");              
                        
   System.out.println("File upload Successfully");

This will also simple way to upload file. I have worked this code in Chrome browser.

Solution 3:[3]

This code worked for me to run the test in BrowserStack. I'm using Java-selenium-Jenkins-BrowserStack

WebElement uploadFile = driver.findElement(By.xpath("//input[@type='file']"));
((RemoteWebElement)uploadFile).setFileDetector(new LocalFileDetector());
        upload_file.sendKeys(System.getProperty("user.dir")+"/src/main/java/resources/common/<Name of your file>.csv");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ANM1996
Solution 2 Cody Gray
Solution 3 fahim reza