【问题标题】:convert dataURL to file using javascript使用javascript将dataURL转换为文件
【发布时间】:2015-01-20 09:32:51
【问题描述】:

在我的一个应用程序中,我使用http://fengyuanchen.github.io/cropper/ 裁剪图像

生成的裁剪图像采用 base64 dataURL 格式,但我要求它采用文件对象格式。

如何在客户端或服务器端将 dataURL 转换为文件。

【问题讨论】:

    标签: java javascript


    【解决方案1】:

    使用Blob 代替已弃用的BlobBuilder。代码非常干净和简单。 (Manuel Di Iorio 的代码已弃用。)

    function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {type:mime});
    }
    //test:
    //var blob = dataURLtoBlob('data:text/plain;base64,YWFhYWFhYQ==');
    

    Data URI scheme

    【讨论】:

    • 从那个?如何将其保存到文件中(保存在本地)? @cuixiping
    • 您可以使用eligrey/FileSaver.js 将文件保存到本地磁盘。 @gumuruh
    【解决方案2】:

    How to convert dataURL to file object in javascript?

    function dataURItoBlob(dataURI) {
        // convert base64 to raw binary data held in a string
        // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
        var byteString = atob(dataURI.split(',')[1]);
    
        // separate out the mime component
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    
        // write the bytes of the string to an ArrayBuffer
        var ab = new ArrayBuffer(byteString.length);
        var ia = new Uint8Array(ab);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
    
        // write the ArrayBuffer to a blob, and you're done
        var bb = new BlobBuilder();
        bb.append(ab);
        return bb.getBlob(mimeString);
    }
    

    然后只需将 blob 附加到新的 FormData 对象并使用 ajax 将其发布到您的服务器:

    var blob = dataURItoBlob(someDataUrl);
    var fd = new FormData(document.forms[0]);
    var xhr = new XMLHttpRequest();
    
    fd.append("myFile", blob);
    xhr.open('POST', '/', true);
    xhr.send(fd);
    

    【讨论】:

      【解决方案3】:

      这就是我对输入的验证。

      $data = $_POST['thumb'];
      $uriPhp = 'data://' . substr($data, 5);
      
      if ( base64_encode(base64_decode($uriPhp))){
          $_POST['thumb'] = $uriPhp;
      } 
      

      为了节省我正在使用:http://www.verot.net/php_class_upload.htm

      $foo = new Upload($_POST['thumb']);
          if ($foo->uploaded) {
            // save uploaded image with a new name
            $foo->file_new_name_body = $name;
            $foo->image_convert = 'png';
            $foo->Process("uploads/");
          }
      

      【讨论】:

        猜你喜欢
        • 2014-10-30
        • 2011-10-14
        • 2018-09-12
        • 2017-03-23
        • 2020-11-12
        • 2013-09-24
        • 2016-03-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多