How would I pass a blob file from Javascript to server code behind in ASP.net

4.3k views Asked by At

I am recording audio on my webpage using recorder.js which is creating a blob that represents a wav file. I want to send this blob file to my c# server code behind so that I can upload it to my azure storage. I've researched a lot on this and could only find results in sending the blob to php. So far, this is the only code I could find to send the blob to code behind:

function upload(blob) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', './addRecord.aspx', true);
    xhr.onload = function (e) {
        var result = e.target.result;
    };
    xhr.send(blob);
}

Then in my addRecord.aspx code behind Page_Load function I have:

Request.SaveAs(Server.MapPath("file.wav"), false);

When I check the file I saved, I cannot open it with anything. The file seems to be corrupted so I assume I wasn't able to pass the file successfully. I've also heard that this could be easy to do by using ajax but I'm not sure how to implement it. I'm open to any ideas on how to do this.

1

There are 1 answers

0
Carlos Guzman On

you can use this techniques:

Base-64

You can read the content from WAV file using FileReader API on javascript, and next coding the binary content to Base-64 to pass this like string chars.

The next is a simple example:

<input type="file" id="files" name="file" />

<script>
    function handleFileSelect(evt) {
        var files = evt.target.files; // FileList object

        // Loop through the FileList and render image files as thumbnails.
        for (var i = 0, f; f = files[i]; i++) {
            // Only process audio files.
            if (!f.type.match('audio.*')) {
                continue;
            }

            var reader = new FileReader();

            // Closure to capture the file information.
            reader.onload = (function(theFile) {
                return function(e) {
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', './addRecord.aspx/MyPostMethod', true);
                    xhr.onload = function (e) {
                        var result = e.target.result;
                    };
                    xhr.send('{"blob":"' + e.target.result + '"}');
                };
            })(f);

            // Read in the image file as a data URL.
            reader.readAsDataURL(f);
        }
    }

    document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

The result is get like Base-64 encoded

I hope this help you