使用HTML5';上传文件;s在Asp.net中拖放
本文关键字:Asp net 拖放 HTML5 使用 文件 | 更新日期: 2023-09-27 18:28:42
我试图使用HTML5的DnD和文件API上传文件。我不确定如何将表单数据发送到服务器,我尝试使用XMLHttpRequest发送,但没有成功。这就是我目前所拥有的。
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<br />
<div id="drop_area">Drop files here</div> <br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button"/>
</form>
</body>
<script>
if (window.File && window.FileList && window.FileReader) {
var dropZone = document.getElementById('drop_area');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleDnDFileSelect, false);
}
else {
alert('Sorry! this browser does not support HTML5 File APIs.');
}
</script>
var files;
function handleDragOver(event) {
event.stopPropagation();
event.preventDefault();
var dropZone = document.getElementById('drop_zone');
dropZone.innerHTML = "Drop now";
}
function handleDnDFileSelect(event) {
event.stopPropagation();
event.preventDefault();
/* Read the list of all the selected files. */
files = event.dataTransfer.files;
/* Consolidate the output element. */
var form = document.getElementById('form1');
var data = new FormData(form);
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
var xhr = XMLHttpRequest();
xhr.open("POST", "Upload.aspx"); //Wrong ? not sure.
xhr.setRequestHeader("Content-type", "multipart/form-data");
xhr.send(data);
}
C#:
HttpFileCollection fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile upload = fileCollection[i];
string filename ="c:''Test''" + upload.FileName;
upload.SaveAs(filename);
}
我知道我在UI中有一个按钮,到目前为止我还没有使用。但是正如您所看到的,我正在尝试使用XMLHttpRequest发送请求。有人能建议我如何继续吗。但我的服务器端代码从未执行过,我不确定XMLHttpRequest是否成功。
Jeezz!!它在IE中运行良好,几天前我就在Chrome v28中进行了测试。在IE文件上传得很好。(测试了多个文件上传)。所以为了让它在Chrome中运行,我不得不做一些更改。*犯的错误
-
镀铬在调试客户端时,我发现var xhr=XMLHttpRequest()抛出错误,"不能将dom对象构造函数作为函数调用"所以换成
var xhr=新的XMLHttpRequest();并删除了xhr.setRequestHeader("内容类型","多部分/表单数据")(不确定原因,但xhr.send()导致ispostback值为false?)
-
欢迎发表意见。链接到完整代码:http://programmingusingdotnet.blogspot.com/2013/08/aspnet-drag-and-drop-file-uploads-using.html