Question

Overview

When dragging and dropping a file onto a page, you can get the file via event.dataTransfer.files when going through all the drag/drop related events. Each file object then has a name attribute.

When pasting a file onto a page, you get the "item" via event.clipboardData.items (which isn't quite an array or an normal object, but I digress) in the onpaste event. The item object then has a getAsFile() method, but this returns a Blob, not a File, so the name attribute is missing.

What I'm trying to do

I would like to get to the filename so I can send it along to store as metadata with the image when I upload the image later.

Is Chrome just buggy?

You would think that they would just reuse event.dataTransfer for this purpose, but that's undefined. You would also think that getAsFile() would return a File, but again the browser makers decided against the obvious. Here are the specs for what getAsFile should do: http://www.w3.org/TR/html/editing.html#dom-datatransferitem-getasfile

Pre-empting some of the inevitable comments:

All this is true at least in Chrome. Let's just say I only care about Chrome and maybe the latest versions of Safari and Firefox for now.

I've seen in comments elsewhere that people seem to think browsers would "never" allow files to be copy/pasted due to "obvious security concerns", yet they do allow them to be dragged and dropped, so let's please skip past that flawed argument.

Conclusion:

Is there any way to get to the pasted file's name? Is this just a bug in Chrome's implementation?

UPDATE

I created a pen on codepen that demonstrates the issue: http://codepen.io/lerouxb/pen/hiLux It also looks like Chrome is at fault here, so I submitted a bug: https://code.google.com/p/chromium/issues/detail?id=361145

Was it helpful?

Solution

Chrome is the only browser that fully implements the Clipboard API. And, as you have noticed, the pasted item is made available as a Blob. It's not 100% clear if this is an error in the implementation of the Clipboard API in Chrome. The spec suggests that it may be, but this has been in place for some time in Chrome, so you'll need to work around it. Another thought here is that there is no file name, since there is no file, just clipboard data. If you want to "name" pasted items, you'll need to solicit input from the user.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top