javascript 如何使用Playwright将文件拖动到拖动区输入元素

0kjbasz6  于 11个月前  发布在  Java
关注(0)|答案(1)|浏览(124)

我有一个用于上传文件的拖拽区输入元素,我正在寻找一种方法来模拟使用Playwright和TS的这种操作。我需要上传许多文件类型,如txtjsonpng


的数据
在剧作家的文献中没有提到这个动作。

ctehm74n

ctehm74n1#

下面是我在GitHub上找到的关于Playwright issue的解决方案

import { Page } from '@playwright/test';
import { readFileSync } from 'fs';

const dragAndDropFile = async (
  page: Page,
  selector: string,
  filePath: string,
  fileName: string,
  fileType = ''
) => {
  const buffer = readFileSync(filePath).toString('base64');

  const dataTransfer = await page.evaluateHandle(
    async ({ bufferData, localFileName, localFileType }) => {
      const dt = new DataTransfer();

      const blobData = await fetch(bufferData).then((res) => res.blob());

      const file = new File([blobData], localFileName, { type: localFileType });
      dt.items.add(file);
      return dt;
    },
    {
      bufferData: `data:application/octet-stream;base64,${buffer}`,
      localFileName: fileName,
      localFileType: fileType,
    }
  );

  await page.dispatchEvent(selector, 'drop', { dataTransfer });
};

字符串
使用示例:(使用this demo-site

test("simulate drag and drop file", async ({ page }) => {
  await page.goto("https://www.dragdrop.com/test/");
  await dragAndDropFile(page, "#demo-upload", "./image1.png", "image1");
});

相关问题