uploadFile method
This method expects elementHandle
to point to an input element.
Sets the value of the file input these paths.
Implementation
Future<void> uploadFile(List<File> files) async {
var isMultiple = await evaluate<bool>('element => element.multiple');
if (files.length > 1 && !isMultiple!) {
throw Exception(
'Multiple file uploads only work with <input type=file multiple>');
}
var objectId = remoteObject.objectId;
var node = await executionContext.domApi.describeNode(objectId: objectId);
// The zero-length array is a special case, it seems that DOM.setFileInputFiles does
// not actually update the files in that case, so the solution is to eval the element
// value to a new FileList directly.
if (files.isEmpty) {
await evaluate('''element => {
element.files = new DataTransfer().files;
// Dispatch events for this case because it should behave akin to a user action.
element.dispatchEvent(new Event('input', { bubbles: true }));
element.dispatchEvent(new Event('change', { bubbles: true }));
}''');
} else {
await executionContext.domApi.setFileInputFiles(
files.map((file) => file.absolute.path).toList(),
objectId: objectId,
backendNodeId: node.backendNodeId);
}
}