客户端代码
<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 包含有关 header 及其内容的信息。 当我分割标题然后保存解码后的内容时,它起作用了...... 我更改了上面的代码,现在可以工作了。谢谢大家
最佳答案
哎呀..有人抢先了我... 当您在客户端读取文件作为 Dataurl 时: reader.readAsDataUrl(...) 该文件被编码为 Base64 字符串。这就是为什么如果直接保存数据,它的格式不正确。 正如前面的答案所述,您将数据进行 base64_decode 为正确的格式。
关于php - html 文件读取器 : convert blob to image file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13023231/