What is the process for combining a javascript fetch function with multipart/form-data for a post request to upload a file?

I need assistance with writing a Java program that utilizes Selenium and the executeAsyncScript() function to upload files to a server. When manually uploading a file, the request in Google Chrome DevTools appears as: Google Chrome Request

The code snippet I have tried is as follows but it is not working:

private void uploadFilesByRest(JSONObject operat) {
    if (operat != null) {
        List<Document> documentsToUpload = config.getOrder().getDocument();
        for (Document document : documentsToUpload) {
            Path pdfPath = Paths.get(document.getPathToFile());
            try {
                byte[] pdfByteArray = Files.readAllBytes(pdfPath);
                sendPdf(jsEngine, pdfByteArray);
            } catch (Exception exc) {
                System.out.println(exc.getMessage());
                LOGGER.error("Error occurred while converting PDF file to byte array");
                System.out.println("Error occurred while converting PDF file to byte array");
            }

        }
    } else {
        LOGGER.error("Operat passed as an argument to the function loading files into component documents has NULL value");
        System.out.println("Operat passed as an argument to the function loading files into component documents has NULL value");
    }
}

public static JSONObject sendPdf(JavascriptExecutor jsEngine, byte[] pdfBlob) {
    Object rsult = jsEngine.executeAsyncScript(
            " var callback = arguments[arguments.length - 1];\n" +
                    "var blob = new Blob([" + pdfBlob + "], {type : 'application/pdf'}); \n" +
                    "var formData = new FormData();\n" +
                    "\n" +
                    "formData.append('FileName', 'sample.pdf');\n" +
                    "formData.append('FileType', '100065');\n" +
                    "formData.append('OwnerId', '54448');\n" +
                    "formData.append('Owner', 'drafts');\n" +
                    "formData.append('File', blob);\n" +
                    "formData.append('files', blob);\n" +
                    "\n" +
                    "fetch('https://example.com/upload', {\n" +
                    "method: 'post',\n" +
                    " headers: {\n" +
                    "'Content-type': 'multipart/form-data',\n" +
                    "}, \n" +
                    "body: formData \n" +
                    " })\n" +
                    ".then(res => res.text())\n" +
                    ".then(res => {\n" +
                    "console.log('response data:');\n" +
                    "console.log(res);\n" +
                    "callback(res);\n" +
                    "}).catch(error => console.log('Error: ', error));"
    );

    JSONObject json = new JSONObject();
    json.put("data", rsult);

    return json;
}

I am seeking guidance on setting a byte array from Java to JS and creating FormData correctly (since Google Chrome DevTools shows multipart/form-data). Currently, my function is producing the error "org.openqa.selenium.JavascriptException: SyntaxError: illegal character". Thank you for your assistance.

Answer №1

My solution is already set. The code provided below is functioning properly. To achieve this, I utilized the java HttpClient class.

private static final String URL = "https://gis.tarnogorski.pl/e-uslugi/portal-archiwisty";
private static final String password = "Tgeodezja11";
private static final String user = "F_OS_ABRZEZINA";
private static WebDriver driver;
private static final String iemz = "P.2413.2004.5";
private static final String forUpdate = "P.2413.2004.5_1";

public static void main(String[] args) throws JsonProcessingException, InterruptedException {
    System.setProperty("webdriver.gecko.driver", ".\\webdriver\\geckodriver-v0.23.0-win64\\geckodriver.exe");
    driver = new FirefoxDriver();
    driver.navigate().to(URL);
    WebDriverWait wait = new WebDriverWait(driver, 40);
    try {
        System.out.println("Waiting for login form");
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(FormEnum.FORMULARZ_LOGOWANIA.getxPath())));
        logIn();
        System.out.println("Logged in successfully");

        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(FormEnum.OKONO_GLOWNE.getxPath()));
        try {
            // Code for handling file upload using HttpClient
            byte[] pdfByteArray = Files.readAllBytes(Paths.get("D:\\Pobrane\\obl_001_P.2413.2001.12.pdf"));

            // Additional logic involving HttpClient setup omitted for brevity...
    
        } catch (Exception olu) {
            System.out.println("Something went wrong");
        }
    } catch (WebDriverException ex) {
        System.out.println("Login error occurred");
    }
}

// Additional utility methods and classes have been omitted for clarity...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining zk and Spring 4 for preauthentication using webseal

Apologies for any language errors. I am encountering an issue while trying to configure a Spring Filter with webseal. I am able to retrieve my user information from the header as "iv-user" (which is the only information I need), but upon redirection to an ...

Troubleshooting Encoding Issues in Docker When using Ubuntu Containers (Python, Java, Ruby, etc.) with Various Encodings (ASCII, UTF-8)

While the application runs smoothly on my personal computer, it encounters issues when deployed in a Docker environment due to invalid characters. The container being used is ubuntu:latest, along with python3, java, and ruby. ...

Explore information from customer feedback on the Daraz platform

This particular code functions perfectly when used on various URLs to extract a product or paragraph. However, it encounters difficulty when attempting to retrieve reviews. import csv from lib2to3.pgen2 import driver from operator import itemgetter from re ...

Retrieving the caret's position in TinyMCE 4

Is there a way to retrieve the caret position in pixels (x & y dimensions) in TinyMCE 4 without obtaining row/column numbers? It should be relative to anything and achieved without adding any extra tags like bookmarks. Anyone know if TinyMCE has a method f ...

"Phraseapp is in the process of refreshing the primary language document

I currently have a locale file that contains various text keys that need to be translated. Each key corresponds to a specific text that needs to be translated into different languages: { key1: "Text to translate", key2: "Another text to translate", ...

What is the best way to loop through the parameter request's value?

I am currently developing a web application that utilizes Spring MVC and Hibernate, Here is the data I have: When submitting a request on the web interface, 'MESSAGEID' is sent, 'MESSAGEID' is not unique, so I need to iterate through ...

How can I set a specific value for a variable that is located within an array?

For instance: var x = y = z = null; var list = [x, y, z]; var number = 10; Is there a way to assign number to x using list, without replacing list[0]? ...

Having difficulty customizing the layout with JavaScript

I want to demonstrate the ability to send a message without hardcoding all messages in my frontend. I utilized existing code from this link shared by another developer. I have included the id="msg" in the input field and id="chatpanel" with class chat-pan ...

Using Vue.js to update the v-bind:style when the mouse hovers over the element

I am working with a span element that displays different background images based on certain conditions. Here is the HTML: <span v-if="type" :style="styles" > </span> In the computed properties section: ...

Tips for creating a visual map using a URL

Here is a code snippet that I found: https://openlayers.org/workshop/en/vector/geojson.html The code requires a URL to a countries.json file, like this: url: './data/countries.json' When I run the code, only zoom in and zoom out buttons appear ...

A guide on writing a Jasmine Unit Test for addEventListener

I'm struggling with writing a Jasmine unit test for AddEventListener. How can I effectively test if the code for addEventListener is functioning correctly? private static disableScrollingOnPageWhenPanelOpen(): void { window.addEventListener('DOMM ...

Enhance table functionality with AngularJs by implementing expandable middle rows

I am developing a payment platform where users can set up a paymentPlan for a specific paymentMethod and choose the number of numberOfIntallments. The details of the paymentPlan are displayed in a table using ng-repeat. Users can select up to 36 numberOfIn ...

Concealing certain columns when the table exceeds a certain size

Hello everyone, I am just starting out in the world of React and web applications. Please feel free to reach out if anything is unclear to you. Here is the table structure that I currently have: <div> <table id="mytableid" className=&qu ...

"Unable to locate the specified file or directory" error message pops up while attempting to save a file

Currently, I am in the process of generating a JSON file using my website with intentions to deploy it later. Below is the code snippet that I have implemented: saveFile = (i, data) => { var filename = `${i}_may.json`; var folder_list = ["desktop", ...

The behavior of Webdriver Selenium can vary depending on the computer it is running

Having written a piece of code to automate tasks using the Webdriver in C#, everything seemed to be running smoothly on my personal computer. However, a perplexing issue arises when the same code behaves differently on my boss's PC. The elusive eleme ...

What is the best way to enter text into the terminal following the execution of "yarn start"?

While developing a Node chat application, I encountered an issue where I am unable to type anything in the terminal after entering "yarn start". The tutorial I am following shows that the instructor can still input commands in their terminal after running ...

Unable to invoke the jQuery datetimepicker function within a personalized directive

I have created a unique time picker directive in AngularJS to display a datetimepicker. app.directive("timePicker", function() { return { restrict: "A", link: function(scope, elem, attrs) { / ...

"Rest API is not activating JavaScript on Android devices, whereas it functions correctly in web browsers

<?php $conn = mysqli_connect('localhost','eyukti_home_roc','4nYntQuCjPYR','eyukti_home_roc'); $user_id = $_GET['user_id']; $sql = mysqli_query($conn,"SELECT * FROM `vehicle_type` WHER ...

Issue with verifying file existence utilizing $.ajax()

I'm currently facing a challenge checking for the existence of a file using $.ajax(). I am cycling through a JSON file with $.each and trying to determine if a specific staff member has an image. If not, I want to default to using the no_photo.jpg ima ...

What is the most effective Xpath for retrieving text from <td> elements when there is text present in both?

I have the following XML that needs to be extracted: <div class="tab_product_details"> <table> <tbody> <tr>...</tr> <tr>...</tr> <tr>...</tr> <tr> ...