【问题标题】:File upload using HTML5's drag and drop in Asp.net在 Asp.net 中使用 HTML5 的拖放上传文件
【发布时间】:2013-08-24 10:49:41
【问题描述】:

我正在尝试使用 HTML5 的 DnD 和 File 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 是否成功。

【问题讨论】:

    标签: c# asp.net html file-upload drag-and-drop


    【解决方案1】:

    天哪!它在 IE 中运行良好,几天以来我一直在 Chrome v 28 中进行测试。在 IE 文件中上传正常。 (测试了多个文件上传)。所以为了让它在 Chrome 中工作,我不得不做一些改变。 * 犯的错误

    【讨论】:

    • 你提供的那个链接对我帮助很大!感谢那。此外,您有没有想过在提交时发送带有 标签的修改(实际调整大小)图像文件?我实际上对此有一个积极的问题:$ stackoverflow.com/questions/20681827/…
    猜你喜欢
    • 2011-09-24
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 2011-10-30
    • 1970-01-01
    • 2011-05-14
    相关资源
    最近更新 更多