Oliver Apel
Oliver Apel

Reputation: 1858

Uploading image to Azure BlobStorage with Javascript

I want to select an image file on my HTML5 Webpage with Input type="file" and send it with jQuery or plain JavaScript to my Azure BlobStorage (secured with SAS).

There are some examples how to do this out in the net. I´ve handled till now everything, what I Need: Creating SAS, sending PUT to BlobStorage with SAS and CORS. My Image is created in BlobStorage. BUT: My file on Azure has a length of 0.

Since my code is working so far, that it created an "empty" file in the cloud, my Problem is now, how I can send the right data to it.

Here´s my Submission:

f_UploadSelectedHandler(evt) {
    var reader = new FileReader();
    reader.onloadend = function (reader_evt) {
        // Here are my tries:
        var mByteArray = reader_evt.target.result;
        //var mByteArray = new Uint8Array(reader_evt.target.result);
        //var mFileData = '';
        //for (var i = 0; i < mByteArray.byteLength; i++) {
        //    mFileData += String.fromCharCode(mByteArray[i]);
        //}
        $.ajax({
            url: mSAS_URL,
            type: "PUT",
            //data: mFileData,
            data: mByteArray,
            headers: {
                "x-ms-blob-type": "BlockBlob",
                "x-ms-date": (new Date()).toUTCString(),
                "Content-Type": mSelectedFileContentType
            },
            success: function (data) {
                alert("done");
            },
            error: function (e, y, s) {
                alert("error");
            }
        })
    }
    reader.readAsArrayBuffer(evt.target.files[0]);
}

If I use var mByteArray = reader_evt.target.result; the uploaded file has a size of 0.

If I use var mByteArray = new Uint8Array(reader_evt.target.result); the uploaded file is corrupted.

If I use var mFileData = ''; for (var i = 0; i < mByteArray.byteLength; i++) { mFileData += String.fromCharCode(mByteArray[i]); } the uploaded file is corrupted.

Every sample I found on the net uses the simplest way:

But so my file is 0. It seems, I have to encode or convert the data from reader_evt.target.result for Azure in some way. Or the reader.readAsArrayBuffer(evt.target.files[0]); is the wrong method. But I´ve tried everything ...

Any ideas?

Upvotes: 1

Views: 1050

Answers (1)

Oliver Apel
Oliver Apel

Reputation: 1858

Got it:

$.ajax({
    url: blobSasUrl,
    type: "PUT",
    data: fileDataAsArrayBuffer,
    processData: false,
    :
    :

The last line was the missing link. I must say to jQuery, to let the data as it is...

Upvotes: 1

Related Questions