-
Notifications
You must be signed in to change notification settings - Fork 3.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Question] How to drag and drop files #10667
Comments
You would be using Web APIs to create File objects and adding them into the datatransfer items, inside the first evaluate. |
@pavelfeldman Can you provide an example? |
Got it. // Read your file into a buffer.
const buffer = readFileSync('./runtime_config/common/file.pdf');
// Create the DataTransfer and File
const dataTransfer = await scope.page.evaluateHandle((data) => {
const dt = new DataTransfer();
// Convert the buffer to a hex array
const file = new File([data.toString('hex')], 'file.pdf', { type: 'application/pdf' });
dt.items.add(file);
return dt;
}, buffer);
// Now dispatch
await page.dispatchEvent('YOUR_TARGET_SELECTOR', 'drop', { dataTransfer }); If you're in TypeScript, add this at the top of your file:
|
Test the real drop interaction! For some reason I couldn't make it work by loading the contents of the respective fixtures into a buffer to produce a file for the DataTransfer object as shown: microsoft/playwright#10667 (comment) Thus using a minimal hardcoded json string (we want to test the drop interaction here, and nothing else, thus it should be fine).
I purpose this for more generic approach. |
I released a utility |
Hi all
(on the webpage there is full page drag& drop function) |
Hi, |
Hi, how to drop images (e.g. PNG) in a certain area? Analogous to the example above? |
Hello, thanks for the info! import base64
def drag_and_drop(page:Page, file_path:str, drop_zone_selector: str) -> None:
with open(file_path, 'rb') as f:
buffer = f.read()
pdf_base64 = base64.b64encode(buffer).decode("utf-8")
# Create the DataTransfer and File
data_transfer = page.evaluate_handle(
"""
(data) => {
const dt = new DataTransfer();
// Convert the binary string to a hexadecimal string
const hexString = Uint8Array.from(atob(data), c => c.charCodeAt(0));
const file = new File([hexString], 'file.pdf', { type: 'application/pdf' });
dt.items.add(file);
return dt;
}
""", pdf_base64
)
# Dispatch the 'drop' event on the target element
page.dispatch_event(drop_zone_selector, 'drop', {"dataTransfer": data_transfer}) |
This works for me on chromium and firefox but fails on webkit with an error that dt.items is undefined. |
Webkit doesn't support creating test('my test', async ({ page }) =>
test.skip(browserName === 'webkit', `Webkit doesn't support creating DataTransfer objects, used for drag and drop`)
// the rest of your test
}) |
This doesn't seem to work for me, so instead of using // ...
await page.evaluateHandle(
(data) => {
const drop = new DragEvent("drop", { dataTransfer: data.data_transfer });
document.querySelector(data.selector).dispatchEvent(drop);
},
{ data_transfer, selector }
); |
Hello everybody! I need to do the same in Java. Please help me! |
@alexeyKoshelevJava byte [] blob;
String fileName = "example.png"
try {
blob = Files.readAllBytes(Paths.get("path/to/file"));
} catch (IOException e) {
throw new RuntimeException(e);
}
// Need to convert byte[] to String like "[116, 101, 115, 116, 51, 57, 48, 52, 54]"
StringJoiner joiner = new StringJoiner(", ", "[", "]");
for (byte b : blob) {
joiner.add(String.valueOf(b));
}
JSHandle dataTransfer = page.evaluateHandle(
"dt = new DataTransfer(); "
+ "file = new File([new Blob([new Uint8Array(" + joiner + ")])], '" + fileName + "'); "
+ "dt.items.add(file); "
+ "dt");
Map<String, Object> arg = new HashMap<>();
arg.put("dataTransfer", dataTransfer);
getElementByName(elementName).dispatchEvent("drop", arg); |
Hi all, is anybody have an example for c# (net.) already spent one day trying to port examples above without sucess. My code
|
Any progress on this? |
Nope. I left this idea to rest in peace. Maybe some rainy day sun will shine a little bit brighter :) |
This seems to work for small (< 10MB files), above this threshold the exact same test will timeout on Are you aware of this limitation and do you have any suggestions to work around this? |
var sourceFilePath = "someDirectory/someFile.doc";
var fileData = await File.ReadAllBytesAsync(sourceFilePath);
var dataTransfer = await Page.EvaluateHandleAsync(
$$"""
(data) => {
const dt = new DataTransfer();
let decodedData = atob(data);
let bytes = new Uint8Array(Array.from(decodedData, char => char.charCodeAt(0)));
let blob = new Blob([bytes], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
file = new File([blob], '{{Path.GetFileName(sourceFilePath)}}', {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
});
dt.items.add(file);
return dt;
}
""",
Convert.ToBase64String(fileData)); |
This code works but on UI I've caught an error that "file type is invalid". public class TestBasePage {
} |
After a lot of issues, this one work best for me
|
How do I write a drag and drop action with a file?
There's an example in the docs that I don't understand
How do I select a file to drag and drop?
The text was updated successfully, but these errors were encountered: