问题
I am uploading files to a website using Selenium 2. I can upload one file by specifying the upload path, but I want to upload all files within a folder. Here's my code:
if (driver.findElements(By.xpath("//input[@type='file']")).size() > 0) {
driver.findElement(By.xpath("//input[@type='file']")).sendKeys("C:\\Users\\Bernard\\Dropbox\\Demo Submission\\Submissions\\Cooley - Imagination Land EP\\Cooley - Imagination Land.mp3");
}
"Cooley - Imagination Land EP" is the folder that contains all the files i want to upload.
I tried "Cooley - Imagination Land EP\*", and a few other things, but this doesn't seem to work.
回答1:
You will need to set the path for each file in the folder not only the folder's path. You can try something like this:
File folder = new File("C:\\Users\\Bernard\\Dropbox\\Demo Submission\\Submissions\\Cooley - Imagination Land EP");
File[] files = folder.listFiles();
String filesList = "";
for(int i = 0; i < files.length;i++){
filesList += (i != 0 ?"\n":"") + files[i].getAbsolutePath();
}
driver.findElement(By.xpath("//input[@type='file']")).sendKeys(filesList);
Also, I think this depends on the type of drive that you're using. For IE you need to surround the paths with quotes and delimit them with a space, for Chrome, you need to delimit them with a new line.
来源:https://stackoverflow.com/questions/34732007/uploading-all-files-in-a-folder-with-windows-file-upload-selenium