Javascript 将上传文件的路径从 HTML5 拖放到输入字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10500362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing path to uploaded file from HTML5 drag & drop to input field
提问by holyredbeard
I'm working on an application (in Node.js, which is irrelevant for this case) which allows the user to upload an image. It works fine using a form with an input (type="file") field.
我正在开发一个允许用户上传图像的应用程序(在 Node.js 中,与本例无关)。使用带有输入 (type="file") 字段的表单可以正常工作。
However, what I want is to be able to upload an image using HTML5 drag and drop instead. As far as i've come it's possible to drag an image to the client, and the image thumbnail is displayed in a div. However I really need some help with getting the file upload working.
但是,我想要的是能够使用 HTML5 拖放来上传图像。就我而言,可以将图像拖动到客户端,并且图像缩略图显示在 div 中。但是,我真的需要一些帮助才能使文件上传工作。
The thing is that I want to use the form that i'm using right now, and (somehow) pass the file's path to the input field, i.e. the flow will work exactly as it do now, but instead of choosing a file by browsing it I want to attach it to the input field by drag and drop.
问题是我想使用我现在正在使用的表单,并且(以某种方式)将文件的路径传递给输入字段,即流程将像现在一样工作,但不是通过浏览选择文件我想通过拖放将它附加到输入字段。
In the js code below for drag and drop the file that was dragged to the client is stored in the variable "file", and i'm able to use "file.name", "file.type" and "file.size" exactly the same way as it works since before with the form. However, I can't access the files "path" (file.path) which makes it impossible to access the file server side for uploading the same way as I do it since before.
在下面用于拖放的 js 代码中,拖放到客户端的文件存储在变量“file”中,我可以使用“file.name”、“file.type”和“file.size”与之前使用表单的工作方式完全相同。但是,我无法访问文件“路径”(file.path),这使得无法像以前那样访问文件服务器端进行上传。
The question is, is it possible to pass the file object to the input field after the file has been dragged to the client, so that I can click on "submit" and upload the file? If so, how could this be done?
问题是,是否可以在将文件拖到客户端后将文件对象传递给输入字段,以便我可以单击“提交”并上传文件?如果是这样,这怎么可能?
Thanks in advance!
提前致谢!
the dropbox as well as the form i'm using for file uploads:
保管箱以及我用于文件上传的表单:
<div id='upload'>
<article>
<div id='holder'>
<p id='status'>File API and FileReader API not supported</p>
</div>
</article>
<form method='post' enctype='multipart/form-data' action='/file-upload'>
<p>
<input type='file' name='thumbnail'>
</p>
<p>
<input type='submit'>
</p>
</form>
</div>
the code for drag and drop:
拖放代码:
uploadImage: function(){
var holder = document.getElementById('holder'),
state = document.getElementById('status');
if (typeof window.FileReader === 'undefined') {
state.className = 'fail';
} else {
state.className = 'success';
state.innerHTML = 'File API & FileReader available';
}
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
this.className = '';
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
holder.style.background = 'url(' + event.target.result + ') no-repeat center';
};
reader.readAsDataURL(file);
return false;
};
},
采纳答案by challet
You cannot use the file input to add the file data. Nevertheless, what you can do (among other technics) is to use the base64 (natively available through the reader.onload event as event.target.result, when using readAsDataURLmethod) encoded data and put it into an hidden field :
您不能使用文件输入来添加文件数据。尽管如此,您可以做的(以及其他技术)是使用 base64(当使用readAsDataURL方法时,通过 reader.onload 事件本地可用作为event.target.result)编码数据并将其放入隐藏字段:
html
html
<article>
<div id='holder'>
<p id='status'>File API and FileReader API not supported</p>
</div>
</article>
<form method='post' enctype='multipart/form-data' action='/file-upload'>
<input type='file' name='thumbnail' />
<input type='hidden' name='base64data' />
<input type='submit' formenctype='application/x-www-form-urlencoded' />
</form>
js
js
reader = new FileReader();
reader.onload = function (event) {
document.getElementById('base64data').setAttribute('value', event.target.result);
};
reader.readAsDataURL(file);
From the server side you'll be able to get the base64 encoded data from the file, just decode it and use it as you want.
从服务器端,您将能够从文件中获取 base64 编码数据,只需对其进行解码并根据需要使用它。
While submitting the form, you could also change the "enctype" attribute (done through the formenctypeattribute) and remove the basic html file input, since the data will be post in a text field.
在提交表单时,您还可以更改“enctype”属性(通过formenctype属性完成)并删除基本的 html 文件输入,因为数据将发布在文本字段中。
回答by SimonKravis
I find that the hidden field set in reader.onload (see answer by @challet) is not set when acccessed in code behind. I am using asp.net and a WebForms project. To access the hidden fields I have to prepend MainContent_ to the field names. aspx code is below
我发现在后面的代码中访问时未设置 reader.onload 中设置的隐藏字段(请参阅@challet 的回答)。我正在使用 asp.net 和一个 WebForms 项目。要访问隐藏字段,我必须在字段名称前加上 MainContent_。aspx代码如下
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
...
<script type="text/javascript">
function dropHandler(ev) {
alert("File(s) dropped");
// Prevent default behavior (Prevent file from being opened)
ev.preventDefault();
//alert("Default prevented");
if (ev.dataTransfer.items) {
if (ev.dataTransfer.items.length > 1) {
alert("Only single files can be dragged and dropped into Caption Pro Web");
return;
}
// If dropped items aren't files, reject them
if (ev.dataTransfer.items[0].kind === 'file') {
var file = ev.dataTransfer.items[0].getAsFile();
document.getElementById("MainContent_DroppedFileName").value = ev.dataTransfer.items[0].name
reader = new FileReader();
reader.onload = function (event) {
document.getElementById('MainContent_DroppedFileContent').value = event.target.result;
};
reader.readAsDataURL(ev.dataTransfer.items[0]);
}
} else {
// Use DataTransfer interface to access the file(s)
if (ev.dataTransfer.files.length > 1) {
alert("Only single files can be dragged and dropped into Caption Pro Web");
return;
}
document.getElementById("MainContent_DroppedFileName").value = ev.dataTransfer.files[0].name
document.getElementById("MainContent_DroppedFileContent").value = "Test";
reader = new FileReader();
reader.onload = function (event) {
document.getElementById("MainContent_DroppedFileContent").value = event.target.result;
};
reader.readAsDataURL(ev.dataTransfer.files[0]);
}
document.getElementById('<%=btnDrop.ClientID %>').click();
}
</script>
...
<div id="drop_zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">
<p>Drag image to this Drop Zone ...</p>
</div>
<asp:HiddenField ID="DroppedFileName" runat="server" />
<asp:HiddenField ID="DroppedFileContent" runat="server" />
...
</asp:Content>
I access the hidden fields from c# as shown below
我从 c# 访问隐藏字段,如下所示
protected void btnDrop_Click(object sender, EventArgs e)
{
string FileName = DroppedFileName.Value;
string FileContent = DroppedFileContent.Value;
}
If I use Internet Explorer as the target browser (not running VS as Admin as this disables drag/drop!) and set a breakpoint in the reader.onload() function the hidden field DroppedFileContent contains the encoded file content, but when I try to access it from btnDrop_Click it only contains "Test" as set before reader.onload() and does not contain the encoded file content. The field DroppedFileNam.Value is as set in the Javascript.
如果我使用 Internet Explorer 作为目标浏览器(不以管理员身份运行 VS,因为这会禁用拖放!)并在 reader.onload() 函数中设置断点,隐藏字段 DroppedFileContent 包含编码的文件内容,但是当我尝试从 btnDrop_Click 访问它,它只包含 reader.onload() 之前设置的“Test”,不包含编码的文件内容。DroppedFileNam.Value 字段在 Javascript 中设置。
回答by seangates
It is impossible to know the path of the field for security purposes. With drag and drop you must have it upload independently of the main form. Look here for an example: http://www.sitepoint.com/html5-file-drag-and-drop/
出于安全目的,不可能知道该字段的路径。通过拖放,您必须独立于主表单上传。在此处查看示例:http: //www.sitepoint.com/html5-file-drag-and-drop/