簡體   English   中英

html FileReader:將blob轉換為圖像文件?

[英]html FileReader : convert blob to image file?

客戶端代碼

<head>
<script>
var reader = new FileReader(); 
var objVal;
var image = new Image();
reader.onload = function(e) {
    document.getElementById('propertyImg').setAttribute('src', e.target.result);
};

function readURL(input){    
    if(input.files && input.files[0]){
        reader.readAsDataURL(input.files[0]);
    }
    else {
        document.images[0].src = input.value || "No file selected";
    }
}

function sendPost(){
            var url = 'http://myurl.com';
            var name = document.getElementById('fileInput').files[0].name;
    var data = document.getElementById('propertyImg').getAttribute('src');
    var f = document.createElement("form"); 
    var imgName = document.createElement("input"); 
    var imgData = document.createElement("input"); 
    var f_attr = { 'method' : 'post' , 'action' : url};
    var imgName_attr = {"type" : "hidden", "name" : "img_name", "value" : name};
    var imgData_attr = {"type" : "hidden", "name" : "data", "value" : data};
    setAttributes(f, f_attr);
    setAttributes(imgName, imgName_attr);
    setAttributes(imgData, imgData_attr);
    f.appendChild(imgName);
    f.appendChild(imgData);
    document.body.appendChild(f); 
    f.submit(); 
}

function setAttributes(el, attrs) {
    for(var key in attrs) {
        el.setAttribute(key, attrs[key]);
    }
}
</script>
<body>
   <img id="propertyImg" src="./img/sprite.png"></img>  
   <input type='file' id='fileInput'class='width70_prop' onchange="readURL(this);"></input>
   <button onclick="sendPost()">sendPost</button>
</body>

服務器端代碼

<html>
    <head>
    <?
          $FileName = $_POST['img_name']; 
          $data = $_POST['data']; 
          list($header, $content) = split('[,]', $data); 
          file_put_contents($FileName, base64_decode($content));
          print "Data Written"; 
     ?>
    <script>
    function showImg(){
    var imgSrc =  "<?=$data?>";
    var imgDiv = document.getElementById('imgDiv');
    imgDiv.src = imgSrc;
    }
    </script>
    </head>
    <body>
    <img id='imgDiv'></img>
    <button onclick="showImg()">show</button>
    </body>
</html>

發送到服務器的blob有關於標題及其內容的信息。 當我分割標題然后保存解碼其內容,它工作....我改變了上面的代碼現在有效。 大家好

首先, $_POST["data"]沒有任何內容,因為索引(數據)由JSON key : value的鍵命名key : value對,而不是JavaScript var

其次,你應該改變這個:

$Handle = fopen($FileName, 'w');
fwrite($Handle, $data); 
print "Data Written"; 
fclose($Handle);

對此:

file_put_contents($FileName, base64_decode($data));

oops ..有人打敗了我......當你在客戶端讀取文件Dataurl:reader.readAsDataUrl(...)時,文件被編碼為base64字符串..這就是為什么如果你直接保存數據,那就是格式不正確。 如前面的答案所述,您可以將數據基於64_decode編碼為正確的格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM