将blob js转换为文件图像php

时间:2016-04-19 20:01:40

标签: javascript php laravel

我尝试使用xhr和FormData()发送DataUri图像, 所以我找到了一个将DataUri转换为blob的方法

  function dataURItoBlob(dataURI) {
        // convert base64/URLEncoded data component to raw binary data held in a string
        var byteString;
        if (dataURI.split(',')[0].indexOf('base64') >= 0)
            byteString = atob(dataURI.split(',')[1]);
        else
            byteString = unescape(dataURI.split(',')[1]);

        // separate out the mime component
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

        // write the bytes of the string to a typed array
        var ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }

我用xhr发送blob var

 var blob = dataURItoBlob(dataURL);
        var data = new FormData();
        data.append('photos[]', blob, "file.png");

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/upload', true);

        xhr.upload.onprogress = function(e) {
            if (e.lengthComputable) {
                var percentComplete = (e.loaded / e.total) * 100;
                console.log(percentComplete + '% uploaded');
            }
        };
        xhr.onload = function() {
                alert(this.response);
                var resp = JSON.parse(this.response);
                console.log('Server got:', resp);

        };
        xhr.send(data);

接下来,我收到了var photos [],我得到了blob对象,但是我不能把它保存为文件

  function storeBlob($blob, $fileName)
    {
        $blobRE = '/^data:((\w+)\/(\w+));base64,(.*)$/';
        if (preg_match($blobRE, $blob, $m))
        {
            $imageName = (preg_match('/\.\w{2,4}$/', $fileName) ? $fileName : sprintf('%s.%s', $fileName, $m[3]));

            return file_put_contents($imageName,base64_decode($m[4]));
        }
        return false; // error
    }

0 个答案:

没有答案