我使用上传功能恢复 pdf 文件,但问题是我收到空文件:
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 });
}
当我在剧作家上传时使用它时,它不起作用,它会在等待 fileChooserPromise 参数中崩溃,因为我不使用输入,我在上传时单击 div:
const fileChooserPromise = page.waitForEvent('filechooser')
await page.getByTestId('fileUpload').click()
const fileChooser = await fileChooserPromise
await fileChooser.setFiles([path.join(__dirname, 'testFile.pdf')])
文件已导入并完成
您正在使用 fs.readFileSync 来读取文件,这是同步的,可能会导致性能问题,特别是在处理大文件时。考虑使用 fs.promises.readFile 进行异步文件读取。
确保从文件缓冲区正确创建 blob。确保缓冲区编码与文件的预期编码相匹配(例如,PDF 文件的二进制编码)。
page.dispatchEvent 需要一个具有 type 和detail 属性的对象。类型应为事件类型(例如“drop”),详细信息应包含事件详细信息。确保您传递正确的活动详细信息。
这是代码的修订版本:
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);
}
};