Trillian
Trillian

Reputation: 411

Uploading a file to a php site using java

I am trying to login to a webpage and upload a file. After searching for a while i found a solution which uses selenium. The html code of the page looks like this:

<html>
  <head><title>some title</title></head>
    <body>
     <h1>upload</h1>
       upload your file<br>
        <form action="hx2.php" method="post" enctype="multipart/form-data">
           <input type="hidden" name="action" value="upload">
           <input type="hidden" name="debug" value="">
           <input type="file" name="filename">
           <input type="submit" value="Datei senden">
           <input type="reset">
        </form>
      </body>
 </html>

and the java code used to login the page and upload my file:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Example_1 {
    public static final String BASEURL = "somesite.de/";
    private static WebDriver driver;
    public static void main(String[] args) {
       String geckoPath = "C:\\...\\gecko\\geckodriver.exe";
       System.setProperty("webdriver.gecko.driver",geckoPath);
       driver = new FirefoxDriver();
       loginAndUpload("uname", "pwd","C:\\...\\myFile.xml");        
    }
    public static void loginAndUpload(String uname, String pwd, String filePath){
        String URL = "http://" + uname + ":" + pwd + "@" + BASEURL;
        driver.get(URL);

        driver.findElement(By.name("filename")).sendKeys(filePath);

        driver.findElement(By.cssSelector("input[type=submit]")).click();
        driver.findElement(By.name("tan")).sendKeys("123");

        driver.findElement(By.cssSelector("input[type=submit]")).click();

        System.out.println(driver.getPageSource().contains("successful")?"successfully uploaded":"upload not successful");
        driver.quit();
    }
}

In order to make this work i needed to download the geckodriver.exe and add 3 external jar files. Additionally, as i am new to selenium, i tried to read something about it and found out that it is a software-testing framework. So my question is: is this a proper way to upload files or am i missusing selenium? If so, is there a simpler/easier way to login a website and upload a file?

Upvotes: 0

Views: 71

Answers (1)

Thilo Schwarz
Thilo Schwarz

Reputation: 782

You should give HttpClient a chance. It is well documented and has a lot of examples. HttpClient is a full implementation of all HTTP methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) in an extensible OO framework. Many authentication schemas are already implemented.

Upvotes: 1

Related Questions