将文件拖放到标准 html 文件输入中
这些天我们可以拖动 &将文件放到一个特殊的容器中,然后使用 XHR 2 上传它们.一次很多.带有实时进度条等.非常酷的东西.此处为示例.
These days we can drag & drop files into a special container and upload them with XHR 2. Many at a time. With live progress bars etc. Very cool stuff. Example here.
但有时我们并不想要那么酷.我想要的是拖动 &将文件(一次很多)放入标准 HTML 文件输入:<input type=file multiple>
.
But sometimes we don't want that much coolness. What I'd like is to drag & drop files -- many at a time -- into a standard HTML file input: <input type=file multiple>
.
这可能吗?有没有办法用正确的文件名(?)从文件拖放中填充"文件输入?(出于文件系统安全原因,完整文件路径不可用.)
Is that possible? Is there some way to 'fill' the file input with the right filenames (?) from the file drop? (Full filepaths aren't available for file system security reasons.)
为什么?因为我想提交一个普通的表单.适用于所有浏览器和所有设备.拖曳&drop 只是渐进式增强来增强 &简化用户体验.带有标准文件输入的标准表单(+ multiple
属性)将在那里.我想添加 HTML5 增强功能.
Why? Because I'd like to submit a normal form. For all browsers and all devices. The drag & drop is just progressive enhancement to enhance & simplify UX. The standard form with standard file input (+ multiple
attribute) will be there. I'd like to add the HTML5 enhancement.
编辑
我知道在 一些 浏览器中,您可以有时(几乎总是)将文件放入文件输入本身.我知道 Chrome 通常会这样做,但有时它会失败,然后将文件加载到当前页面中(如果你正在填写表格,那就大失败了).我想愚弄-&浏览器证明它.
edit
I know in some browsers you can sometimes (almost always) drop files into the file input itself. I know Chrome usually does this, but sometimes it fails and then loads the file in the current page (a big fail if you're filling out a form). I want to fool- & browserproof it.
推荐答案
以下在 Chrome 和 FF 中有效,但我还没有找到涵盖 IE10+ 的解决方案:
The following works in Chrome and FF, but i've yet to find a solution that covers IE10+ as well:
// dragover and dragenter events need to have 'preventDefault' called
// in order for the 'drop' event to register.
// See: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Drag_operations#droptargets
dropContainer.ondragover = dropContainer.ondragenter = function(evt) {
evt.preventDefault();
};
dropContainer.ondrop = function(evt) {
// pretty simple -- but not for IE :(
fileInput.files = evt.dataTransfer.files;
// If you want to use some of the dropped files
const dT = new DataTransfer();
dT.items.add(evt.dataTransfer.files[0]);
dT.items.add(evt.dataTransfer.files[3]);
fileInput.files = dT.files;
evt.preventDefault();
};
<!DOCTYPE html>
<html>
<body>
<div id="dropContainer" style="border:1px solid black;height:100px;">
Drop Here
</div>
Should update here:
<input type="file" id="fileInput" />
</body>
</html>
您可能希望使用 addEventListener
或 jQuery(等)来注册您的 evt 处理程序 - 这只是为了简洁起见.
You'll probably want to use addEventListener
or jQuery (etc.) to register your evt handlers - this is just for brevity's sake.
相关文章