skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. Here’s a revised version of your code:

    const fs = require('fs').promises;
    
    const uploadFile = async (page, documentPathCopy) => {
    
    
    try {
    // Read the file asynchronously
    const buffer = await fs.readFile(documentPathCopy);
    
    // Create the DataTransfer and File
    const dataTransfer = await page.evaluateHandle((data) => {
      const dt = new DataTransfer();
      const blob = new Blob([data], { type: 'application/pdf' });
      const file = new File([blob], 'testFile.pdf', { type: 'application/pdf' });
      dt.items.add(file);
      return dt;
    }, buffer);
    
    // Dispatch the 'drop' event with the dataTransfer
    await page.dispatchEvent('[data-testid="fileUpload"]', 'drop', { dataTransfer });
    
    console.log('File uploaded successfully');
    } catch (error) {
    console.error('Error uploading file:', error);
    }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search