I am trying to upload an excel file using XMLHttpRequest and FormData in ASP.NET but always I am getting Request.FIles as null in ASP.NET, here is my code please help me,
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>
Server Side in Asp.net page
protected void Page_Load(object sender, EventArgs e)
{
try
{
var aa = FindControl("ImportFcpFile");
HttpPostedFile file = Request.Files["ImportUserExcelFile"];
}
catch (Exception ex)
{
}
}
here is what I do
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);
}
}
This the javascript code i used. i think you have missed some things
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);
}
I just iterate through the files and save it with whatever name i want
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.