Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(add) feature for uploading files to remote webdriver #317

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions remote.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,18 @@
package selenium

import (
"archive/zip"
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
Expand Down Expand Up @@ -249,6 +252,64 @@ func DeleteSession(urlPrefix, id string) error {
return voidCommand("DELETE", u.String(), nil)
}

// Upload a files to remote WebDriver
// Returns directory which uploaded files
func (wd *remoteWD) UploadFiles(filenames ...string) (string, error) {
var buf bytes.Buffer
zipped := zip.NewWriter(&buf)

for _, filename := range filenames {
w, err := zipped.Create(filename)
if err != nil {
return "", err
}

r, err := os.Open(filename)
if err != nil {
return "", err
}

fBuf, err := io.ReadAll(r)
if err != nil {
return "", err
}

if _, err := w.Write(fBuf); err != nil {
return "", err
}
}

zipped.Close()

payload, err := json.Marshal(map[string]interface{}{
"file": buf.Bytes(),
})

if err != nil {
return "", err
}

resp, err := wd.execute("POST",
wd.requestURL("/session/%s/file", wd.id),
payload,
)
if err != nil {
return "", err
}

responseData := map[string]interface{}{}
if err := json.Unmarshal(resp, &responseData); err != nil {
return "", err
}

directory, ok := responseData["value"].(string)
if !ok {
return "", fmt.Errorf("nil return value")
}

return directory, nil
}

func (wd *remoteWD) stringCommand(urlTemplate string) (string, error) {
url := wd.requestURL(urlTemplate, wd.id)
response, err := wd.execute("GET", url, nil)
Expand Down
3 changes: 3 additions & 0 deletions selenium.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,9 @@ type WebDriver interface {
// Quit ends the current session. The browser instance will be closed.
Quit() error

// Uploads files to remote WebDriver
UploadFiles(filenames ...string) (string, error)

// CurrentWindowHandle returns the ID of current window handle.
CurrentWindowHandle() (string, error)
// WindowHandles returns the IDs of current open windows.
Expand Down