Reputation: 13
I'm building an electron app. One of my features is to drag and drop any files to store them into the electron & vue app.
It works well with local files stored on my computer. I can't do the same with files from a web browser (till now I've tried in Chrome).
I use the dragover
and ondrop
events to check the file's data. With files from browser I don't have any data in those events.
export default {
name: 'colors',
mounted () {
document.ondragover = document.ondrop = (ev) => {
ev.preventDefault()
// console.log(ev)
}
document.body.ondrop = (ev) => {
console.log(ev)
ev.preventDefault()
}
}
}
Any ideas?
Thanks
Upvotes: 0
Views: 1438
Reputation: 11
The starting point you're looking for is event.dataTransfer.getData('url')
.
When you drag an image from the browser into your Electron app, the "data" you're handed is a URL string pointing to the image. It's accessed by calling the getData()
method, and passing in "url" as the DOMString.
So with your example, to get the url to the image you just dragged in, you'd do
document.body.ondrop = (ev) => {
ev.preventDefault();
const imageUrl = ev.dataTransfer.getData('url');
// will set imageUrl equal to something like "https://somewebsite.com/your-image.jpg"
}
This MDN article explains working with dataTransfer's getData()
in a bit more detail, but they don't mention exactly which arguments you can pass to getData()
. If you dig into the W3C spec for HTML5 Drag and Drop, you'll see that it accepts a string of either "text" or "url". You'd use "text" if you were dragging and dropping a link or text block into your app, and "url" for images.
According to the W3C spec:
If format equals "text", change it to "text/plain".
If format equals "url", change it to "text/uri-list" and set convert-to-URL to true.
So what do you do once you have that URL? Well, you would need to download the image by streaming it to a file, and that will give you the actual image file on your computer to be moved/renamed/whatever by your app. Assuming you're using a library like Request:
function downloadImage(imageUrl) {
request({ url: imageUrl, encoding: null }, (err, httpResponse, body) => {
if (err) throw err;
const destination = 'some/app/folder/image.jpg;
fs.createWriteStream(destination).write(body);
});
}
Upvotes: 1