Request.Files即将为空ASP.NET

时间:2016-08-25 08:25:06

标签: javascript asp.net ajax

我试图在ASP.NET中使用XMLHttpRequest和FormData上传一个excel文件,但我总是在ASP.NET中将Request.FIles作为null,这里是我的代码请帮帮我,

function BulkUploadUsers(e){
    var url = "/BC/Product/Modules/UserManagement/BulkUpload.aspx?action=import";
    var fd = new FormData();
    fd.append("ImportWorkOrderExcelFile", document.getElementById('ctl01_ImportFcpFile').files[0]);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.setRequestHeader('X-CSRF-Token', document.getElementById("_RequestVerificationToken").value);
    xhr.setRequestHeader("Content-Type", "multipart/form-data");
    xhr.send(fd);
}
    <div>
        <input type="file" id="ImportFcpFile" runat="server"  onchange="BulkUploadUsers(this)"/>       
    </div>

Asp.net页面中的服务器端

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
                var aa = FindControl("ImportFcpFile");
                HttpPostedFile file = Request.Files["ImportUserExcelFile"];

        }
        catch (Exception ex)
        {
        }
    }

1 个答案:

答案 0 :(得分:0)

这是我做的事情

HttpFileCollection fileCollection = HttpContext.Current.Request.Files;
string savedfile = "";
            for (int i = 0; i < fileCollection.Count; i++)
            {
                try
                {
                    HttpPostedFile upload = fileCollection[i];
                    int f = fileCollection[i].ContentLength;
                    string filename = "/ProductImages/" + fileCollection[i].FileName;
                    upload.SaveAs(Server.MapPath(filename));
                    savedfile += fileCollection[i].FileName;
                }
                catch (Exception ex)
                {
                    List<string> ff = new List<string>();
                    ff.Add(ex.Message.ToString());
                    System.IO.File.WriteAllLines(Server.MapPath("/ProductImages/Error.txt"), ff);
                }

            }

这是我使用的javascript代码。我想你错过了一些事情

      function handleDnDFileSelect(event) {


           /* Read the list of all the selected files. */
          var files = event.dataTransfer.files;

           /* Consolidate the output element. */
           var form = document.getElementById('form1');

         var  fd= new FormData(form);

          for (i = 0; i < files.length; i++) {
               fd.append(files[i].name, files[i]);
           }
           var xhr = new XMLHttpRequest();
         xhr.onreadystatechange = function () {
             if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText) {
                 alert("upload done!");
             } else {
                 //alert("upload failed!");
             }
         };
         xhr.open('POST', "/BC/Product/Modules/UserManagement/BulkUpload.aspx");
        // xhr.setRequestHeader("Content-type", "multipart/form-data");
         xhr.send(fd);

        }

我只是遍历文件并以我想要的名字保存它