Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send ArrayBuffer with other string in one Ajax call through jQuery

I'm working on a project need to upload large file to server side. I decided to use HTML5 FileReader and jQuery to upload the file in chunks (ArrayBuffer).

I successfully finished this task by converting the chunks into base64 string, send to backend server through jQuery.post with the data parameter in JSON format.

For example

$.ajax({
    url: "/Home/Upload",
    type: "POST",
    data: {
        name: block.name,
        index: block.index,
        base64: base64
    },
    processData: true
});

But I'd like to optimize this code since base64 is too large to transform. I'd like to know if I could send ArrayBuffer directly through $.ajax.

I know that if I set the processData: false and just put ArrayBuffer into data parameter it could be sent to my server side as Request.InputStream. But in this way I cannot attach other data such as name and index.

I'd like to know may I send the raw ArrayBuffer (or blob, binary) alone with my other data (name, index) in one ajax call.

like image 852
Shaun Xu Avatar asked Jun 26 '13 09:06

Shaun Xu


1 Answers

I think I had got this issue resolved. I can use FormData to transform my structured data alone with file binary in one form. Code like this

var blob = file.slice(block.start, block.end);
// use formdata to send block content in arraybuffer
var fd = new FormData();
fd.append("name", block.name);
fd.append("index", block.index);
fd.append("file", blob);
$.ajax({
    url: "/Home/UploadInFormData",
    data: fd,
    processData: false,
    contentType: "multipart/form-data",
    type: "POST",
    success: function (result) {
        if (!result.success) {
            alert(result.error);
        }
        callback(null, block.index);
    }
});

Then from server side I can retrieve my structured data from Request.Form while the binary content from Request.Files[0]

like image 159
Shaun Xu Avatar answered Sep 17 '22 08:09

Shaun Xu