3

I'm trying to upload some text content via ajax, that will be parsed later. That 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 is my file input, and testhandler.ashx is the server handler that gets the uploaded file. (I actually use another handler to parse the file content.)

BUT when I try to do this:

HttpFileCollection fc = context.Request.Files;

It returned no files. But Works in IE for some reason.

But when I try to get the input stream:

    StreamReader stream = new StreamReader(context.Request.InputStream);
    string text = stream.ReadToEnd();

The text variable become (Http Headers) + File Content.

------WebKitFormBoundaryx16Mw7tnG6JeflIB\r\nContent-Disposition: form-data;name=\"file\"; filename=\"teste export.CSV\"\r\nContent-Type: application/vnd.ms-excel(..file content..)

That's OK, but I've used this plugin: http://valums.com/ajax-upload/

And the plugin returned me only the file content, in witch I could get the content via InputStream, I didn't received any HTTP header.

That's PERFECT, but I want to make a Upload script without using plugins. Just upload and parse, returning some results. Simple and fast

So, My question is: How to get the file content, uploaded by Ajax XHR, getting ONLY the file content, in any browser?

1 Answers1

0

It's work for me and I think it can help you

My js function :

$("#fuFile").click(function () {
    var fileInput = document.getElementById("fuFile");
    var file = fileInput.files[0];
    var fd = new FormData();
    fd.append("files", file);
    var xhr = new XMLHttpRequest();

    xhr.open("POST", 'http://localhost:63186/UploadFile.ashx');

    xhr.send(fd);

});

My handler :

  string filePath = "~/Files/";

        //write your handler implementation here.
        if (context.Request.Files.Count <= 0)
        {
            context.Response.Write("No file uploaded");
        }
        else
        {
            for (int i = 0; i < context.Request.Files.Count; ++i)
            {
                HttpPostedFile file = context.Request.Files[i];
                 var fileInfo = new FileInfo(file.FileName);
                file.SaveAs(context.Server.MapPath(filePath + fileInfo.Name));
                context.Response.Write("File uploaded");
            }
        }
Alex Nguyen
  • 1,032
  • 12
  • 27