I use the upload function to recover a pdf file but the problem I receive the empty file :
const uploadFile= async (page,documentPathCopy)=>{
const buffer = fs.readFileSync(documentPathCopy,'utf8');
// Create the DataTransfer and File
let dataTransfer = await page.evaluateHandle((data) => {
let dt = new DataTransfer();
// Convert the buffer to a hex array
const blob = new Blob([data]);
const file = new File([blob], 'testFile.pdf', { type: 'application/pdf' });
console.log("data ", data)
dt.items.add(file);
return dt;
}, buffer);
await page.dispatchEvent('[data-testid="fileUpload"]','drop',{ dataTransfer });
}
and when I use this when playwright for the upload it does not work it crashes in await fileChooserPromise aparament because I use not an input I click on a div when I upload:
const fileChooserPromise = page.waitForEvent('filechooser')
await page.getByTestId('fileUpload').click()
const fileChooser = await fileChooserPromise
await fileChooser.setFiles([path.join(__dirname, 'testFile.pdf')])
file is import and complete
2
Answers
You’re using fs.readFileSync to read the file, which is synchronous and may cause performance issues, especially if you’re dealing with large files. Consider using fs.promises.readFile for asynchronous file reading.
Make sure that the blob is created correctly from the file buffer. Ensure that the buffer encoding matches the expected encoding of the file (e.g., binary for PDF files).
page.dispatchEvent requires an object with the type and detail properties. The type should be the event type (e.g., ‘drop’), and the detail should contain the event details. Ensure you’re passing the correct event details.
Here’s a revised version of your code: