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.