jQuery追加blob来序列化数据

时间:2017-02-09 09:39:44

标签: jquery

我有这段代码:

var blob= base64ToBlob(cover, 'image/jpg');
var data = $(this).serializeArray();

如何将blob值附加到serializeArray()

我尝试使用data.push(blob, blob),当服务器收到该值为空时。

任何解决方案?

$('#form').on('submit', function (e) {
    e.preventDefault();
    var avatar = $('.avatar-editor').cropit('export');
    var cover = $('.cover-editor').cropit('export');


    var avatarContent = replace64(avatar);
    var avatarBlob = base64ToBlob(avatarContent, 'image/jpg');

    var coverContent = replace64(cover);
    var coverBlob = base64ToBlob(coverContent, 'image/jpg');

    var formData = new FormData($(this)[0]);
    formData.append(avatar, avatarBlob);
    formData.append(cover, coverBlob);


    var url = '/people';

    axios.post(url, formData)
        .then(function (response) {
            $.ladda('stopAll');

            var data = response.data;
            if (data.code == 200) {
                location.reload();
                return true;
            }

            swal(data.error.title, data.error.message, 'error');

        })
        .catch(function (response) {
            $.ladda('stopAll');
        })
});

当提交是时,有头像和封面,但值为空。

这是我的blob函数

function replace64(image) {
    return image.replace(/^data:image\/(png|jpg);base64,/, "");
}

function base64ToBlob(base64, mime) {
    mime = mime || '';
    var sliceSize = 1024;
    var byteChars = window.atob(base64);
    var byteArrays = [];

    for (var offset = 0, len = byteChars.length; offset < len; offset += sliceSize) {
        var slice = byteChars.slice(offset, offset + sliceSize);

        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        var byteArray = new Uint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

    return new Blob(byteArrays, {type: mime});
}

在使用Laravel 5.3的服务器上,只需简单返回查看我控制台上的数据:

return $request()->all();

0 个答案:

没有答案