NỘI DUNG BÀI HỌC

Xử lý upload file trong Selenium Java (Handle Upload File in Selenium Java)

Có 2 cách upload file An thấy nó dễ dàng mà hiệu quả cho nhiều case upload là: dùng sendKeys của Selenium và dùng cách copy paste link file từ clipboard vào Local form hiện lên từ Computer với Robot class.

Ok mình sẽ đi từng cách nhé !!

1. Upload file với sendKeys trong Selenium

Điều kiện tiên quyết để dùng được cách này là:
- Element phải là thẻ "input" và có type là "file". Nhưng cần kiểm tra là nó cho phép kéo thả file vào (thử thủ công trước)
- File PATH là đường dẫn tuyệt đối, phải tính từ thư mục ổ đĩa máy tính cho đến file name chấm đuôi file chính xác
- Dùng dấu \\ để phân cách folder nếu link trực tiếp trong ổ đĩa máy tính Windows
- Suggest: nên mang file vào cùng project để file PATH nó ổn định cho nhiều máy

Cách này các bạn dùng hàm sendKeys với giá trị là một link file tuyệt đối từ local máy là xong

    @Test
    public void testUploadFileWithSendKeys() throws InterruptedException {
        driver.get("https://cgi-lib.berkeley.edu/ex/fup.html");

        Thread.sleep(2000);

        By inputFileUpload = By.xpath("//input[@name='upfile']");
        
        driver.findElement(inputFileUpload).sendKeys(System.getProperty("user.dir") + "/datatest/Selenium4_Upload.png");

        Thread.sleep(4000);
    }


Chú ý cái System.getProperty("user.dir") nghĩa là nó lấy từ mục gốc của máy tính (C:/, D:/, ...) tới mục của source code mình đang mở và sau đó nối vào cái thư mục nguồn src trở về sau.


2. Upload file với Robot class của Java

Ý tưởng:
- Click button mở form chọn file từ máy tính
- Copy link file đó vào clipboard
- Dán giá trị từ clipboard đó (Ctrl + V)
- Nhấn phím Enter

Ok vậy là xong rồi. Thử đoạn code này nào.

@Test
public void testUploadFile2() throws InterruptedException {
  driver.get("https://files.fm/");

  Thread.sleep(2000);

  By textOnPage = By.xpath("//div[@id='file_select_dragndrop_text']");
  By divFileUpload = By.xpath("//div[@id='uploadifive-file_upload']");
  By inputFileUpload = By.xpath("//div[@id='file_select_button']//input[@id='file_upload']");

  String filePath = "C:\\Users\\Admin\\Pictures\\Selenium icon.png";

  //Click để mở form upload
  driver.findElement(divFileUpload).click();
  Thread.sleep(3);

  // Khởi tạo Robot class
  Robot rb = null;
  try {
    rb = new Robot();
  } catch (AWTException e) {
    e.printStackTrace();
  }

  // Copy File path vào Clipboard
  StringSelection str = new StringSelection(filePath);
  Toolkit.getDefaultToolkit().getSystemClipboard().setContents(str, null);

  Thread.sleep(1000);

  // Nhấn Control+V để dán
  rb.keyPress(KeyEvent.VK_CONTROL);
  rb.keyPress(KeyEvent.VK_V);

  // Xác nhận Control V trên
  rb.keyRelease(KeyEvent.VK_CONTROL);
  rb.keyRelease(KeyEvent.VK_V);

  Thread.sleep(1000);

  // Nhấn Enter
  rb.keyPress(KeyEvent.VK_ENTER);
  rb.keyRelease(KeyEvent.VK_ENTER);

  Thread.sleep(4000);
}


Upload File trong Selenium Java | Anh Tester

Từ 2 hàm trên thì các bạn viết 2 hàm chung cho nó rồi truyền vào ElementFile Path là đẹp hơn đó.


----------------------------------------------------------------------
Code theo Page Object Model + WebUI keyword

Thực hành trên hệ thống CMS: https://demo.activeitzone.com/ecommerce/login

Class: UploadFileCMSPage (page)

package anhtester.com.pages;

import anhtester.com.helpers.Helpers;
import anhtester.com.utils.WebUI;
import org.openqa.selenium.By;

import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

public class UploadFileCMSPage {

    //Login
    private By buttonCopy = By.xpath("//button[normalize-space()='Copy']");
    private By buttonLogin = By.xpath("//button[normalize-space()='Login']");

    //Category
    private By menuProducts = By.xpath("//span[normalize-space()='Products']");
    private By menuCategory = By.xpath("//span[normalize-space()='Category']");
    private By butttonAddNewCategory = By.xpath("//span[normalize-space()='Add New category']");
    private By chooseFile = By.xpath("//label[normalize-space()='Banner (200x200)']/following-sibling::div//div[normalize-space()='Choose file']");
    private By buttonUploadNew = By.xpath("//a[normalize-space()='Upload New']");
    private By buttonBrowse = By.xpath("//button[normalize-space()='Browse']");
    private By buttonAddFiles = By.xpath("//button[normalize-space()='Add Files']");
    private By messageComplete = By.xpath("//div[@class='uppy-StatusBar-statusPrimary']");

    private By buttonSelectFile = By.xpath("//a[normalize-space()='Select File']");
    private By inputSearchFile = By.xpath("//input[@placeholder='Search your files']");
    private By itemFile = By.xpath("(//div[@class='card-body']//h6)[1]");

    public void loginCMS() {
        WebUI.openURL("https://demo.activeitzone.com/ecommerce/login");
        WebUI.clickElement(buttonCopy);
        WebUI.clickElement(buttonLogin);
    }

    public void uploadFileInCategory() {
        WebUI.waitForPageLoaded();
        WebUI.clickElement(menuProducts);
        WebUI.clickElement(menuCategory);
        WebUI.clickElement(butttonAddNewCategory);
        WebUI.clickElement(chooseFile);
        WebUI.clickElement(buttonUploadNew);
        WebUI.clickElement(buttonBrowse); //Mở form select file từ local PC

        //Dán đoạn code dùng Robot class để hành động với bàn phím
        // Khởi tạo Robot class
        Robot rb = null;
        try {
            rb = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }

        String filePath = Helpers.getCurrentDir() + "datatest\\Selenium4_Upload.png";

        // Copy File path vào Clipboard
        StringSelection str = new StringSelection(filePath);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(str, null);

        WebUI.sleep(1);

        // Nhấn Control+V để dán
        rb.keyPress(KeyEvent.VK_CONTROL);
        rb.keyPress(KeyEvent.VK_V);

        // Xác nhận Control V trên
        rb.keyRelease(KeyEvent.VK_CONTROL);
        rb.keyRelease(KeyEvent.VK_V);

        WebUI.sleep(2);

        // Nhấn Enter
        rb.keyPress(KeyEvent.VK_ENTER);
        rb.keyRelease(KeyEvent.VK_ENTER);

        WebUI.sleep(3);
        WebUI.clickElement(buttonSelectFile);
        WebUI.setText(inputSearchFile, "Selenium4_Upload");
        WebUI.sleep(1);
        WebUI.clickElement(itemFile);
        WebUI.sleep(1);
        WebUI.clickElement(buttonAddFiles);
        WebUI.sleep(2);
    }

}


Class: UploadFileCMS (test case)

package anhtester.com.testcases;

import anhtester.com.common.BaseTest;
import anhtester.com.helpers.Helpers;
import anhtester.com.pages.UploadFileCMSPage;
import anhtester.com.utils.WebUI;
import org.openqa.selenium.By;
import org.testng.annotations.Test;

public class UploadFileCMS extends BaseTest {

    @Test
    public void testUploadFileWithSendKeys() throws InterruptedException {
        WebUI.openURL("https://cgi-lib.berkeley.edu/ex/fup.html");
        WebUI.waitForPageLoaded();
        By inputFileUpload = By.xpath("//input[@name='upfile']");

        //DriverManager.getDriver().findElement(inputFileUpload).sendKeys(Helpers.getCurrentDir() + "datatest/Selenium4_Upload.png");
        WebUI.setText(inputFileUpload, Helpers.getCurrentDir() + "datatest/Selenium4_Upload.png");
        Thread.sleep(3000);
    }

    @Test
    public void testUploadFileInCategoryCMS() {
        UploadFileCMSPage uploadFileCMSPage = new UploadFileCMSPage();
        uploadFileCMSPage.loginCMS();
        uploadFileCMSPage.uploadFileInCategory();
    }

}



Ok rồi. Có gì chưa hiểu hay chưa làm được thì liên hệ An trong nhóm nhé !!

Teacher

Teacher

Anh Tester

Software Quality Engineer

Đường dẫu khó chân vẫn cần bước đi
Đời dẫu khổ tâm vẫn cần nghĩ thấu

Cộng đồng Automation Testing Việt Nam:

🌱 Telegram Automation Testing:   Cộng đồng Automation Testing
🌱 
Facebook Group Automation: Cộng đồng Automation Testing Việt Nam
🌱 
Facebook Fanpage: Cộng đồng Automation Testing Việt Nam - Selenium
🌱 Telegram
Manual Testing:   Cộng đồng Manual Testing
🌱 
Facebook Group Manual: Cộng đồng Manual Testing Việt Nam

Chia sẻ khóa học lên trang

Bạn có thể đăng khóa học của chính bạn lên trang Anh Tester để kiếm tiền

Danh sách bài học