I am attempting to upload text content using ajax for later parsing. Here is my JavaScript code:
$("#fuFile").change(function () {
var fileInput = document.getElementById("fuFile");
var file = fileInput.files[0];
var formdata = new FormData();
formdata.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'testhandler.ashx', true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.send(formdata);
});
Where fuFile
represents the file input, and testhandler.ashx
is the server handler responsible for receiving the uploaded file. (I actually utilize another handler to parse the file content.)
However, when I attempt this:
HttpFileCollection fc = context.Request.Files;
No files are returned. It does work in IE for some reason.
Yet, if I try to access the input stream:
StreamReader stream = new StreamReader(context.Request.InputStream);
string text = stream.ReadToEnd();
The text
variable ends up containing both the HTTP headers and the File Content.
------WebKitFormBoundaryx16Mw7tnG6JeflIB\r\nContent-Disposition: form-data;name=\"file\"; filename=\"teste export.CSV\"\r\nContent-Type: application/vnd.ms-excel(..file content..)
Although this is acceptable, I have previously utilized a plugin:
This plugin only provided me with the file content, from which I could retrieve data via InputStream without any HTTP header received.
This solution was ideal, but I aim to create an upload script that doesn't rely on plugins. Simply upload, parse, and return results. Efficient and straightforward.
Hence, my query is: How can I extract the file content exclusively from an Ajax XHR upload, across all browsers?