开发者

Javascript: Is there a way to get the filename of the dragged-in file?

When user drags in a file, is there a 开发者_StackOverflowway in Javascript to detect its filename onDragEnter (not after it's uploaded)?


Not every browser supports dragging files to a file input (FF4 on OS X certainly doesn't), but you can check the value of the file input on change event, which should provide a uniform result across browsers.

Depending on the browser, you can check the value of

<input type="file" id="foo" />

like so:

// vanilla JS
var filename = document.getElementById('foo').value;

// jQuery
var filename = $('#foo').val();

You'd do this inside of a change listener, like so (example for jQuery in jsFiddle below):

function alertFileName()
{
    alert(this.value);
}

var input = document.getElementById('foo');

// not IE friendly; use `attachEvent` instead
input.addEventListener('change', alertFilename, false);

If you upload a file named bar.txt, filename will be:

  • 'C:\fakepath\bar.txt' (Chrome)
  • 'bar.txt' (Firefox 4, Safari)
  • ??? (IE)

I am not set up to test IE at present; feel free to try it yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜