我想从Blob网址或数据中保存或下载图像

时间:2019-06-11 04:03:29

标签: javascript php blob

im从剪贴板执行粘贴事件,它会创建一个Blob网址。现在我不知道如何保存或获取文件。如何将其保存到计算机上?我认为在将blob添加到我的php中是完全错误的。我将其作为字符串获取,然后尝试保存它

这是我用于创建Blob的代码

<?php 
if( isset( $_FILES['file'] ) ) {
    $file_contents = file_get_contents( $_FILES['file']['tmp_name'] );
    header("Content-Type: " . $_FILES['file']['type'] );
    die($file_contents);
}
else {
    header("HTTP/1.1 400 Bad Request");
}
print_r($_FILES);
?>

<script type="text/javascript">
document.onpaste = function (e) {
    var items = e.clipboardData.items;
    var files = [];
    for( var i = 0, len = items.length; i < len; ++i ) {
        var item = items[i];
        if( item.kind === "file" ) {
            submitFileForm(item.getAsFile(), "paste");
        }
    }

};

function submitFileForm(file, type) {
    var extension = file.type.match(/\/([a-z0-9]+)/i)[1].toLowerCase();
    var formData = new FormData();
    formData.append('file', file, "image_file");
    formData.append('extension', extension );
    formData.append("mimetype", file.type );
    formData.append('submission-type', type);

    var xhr = new XMLHttpRequest();
    xhr.responseType = "blob";
    xhr.open('POST', '<?php echo basename(__FILE__); ?>');
    xhr.onload = function () {
        if (xhr.status == 200) {
           var img = new Image();

            img.src = (window.URL || window.webkitURL)
                .createObjectURL( xhr.response );
            document.getElementById("nye").appendChild(img);
             document.getElementById("nye").style.display = "none" ;
            var x = document.getElementById("image");
  x.setAttribute("type", "text");
  x.setAttribute("value", img.src);
  document.getElementById("image").appendChild(x);



        }
    };

    xhr.send(formData);
}
</script>

这是我的代码,已保存到我的计算机上,它可以运行,但我无法接收到空白的jpg文件

<?php
  $data = $_POST['url'];
  $filePath = $uploadDir . $name;

  $contents_split = explode(',', $data);
  $encoded = $contents_split[count($contents_split)-1];
  $decoded = "";
  for ($i=0; $i < ceil(strlen($encoded)/256); $i++) {
    $decoded = $decoded . base64_decode(substr($encoded,$i*256,256)); 
  }

  $fp = fopen('sample23.jpg', 'w');
  fwrite($fp, $decoded);
  fclose($fp);
?>

它保存,但我认为该文件为空。

0 个答案:

没有答案