Blob(Binary Large Object)是一种 JavaScript 的数据类型,用于存储大量的二进制数据。Blob 对象中存储的数据没必要非得是 JavaScript 原生格式数据(或者没必要是 JavaScript 内部对象),例如,可以是 File 对象,它继承 Blob 对象,是 Blob 的一个分支或者说是一个子集。
在 JavaScript 中,所有 File 对象都是一个 Blob 对象,因此可以通过发送 Blob 对象的方法来发送文件。
【示例】下面示例在页面中显示一个“复制文件”按钮和一个进度条(progress 元素),单击“复制按钮”后,JavaScript 使用当前页面中所有代码创建一个 Blob 对象,然后通过将该 Blob 对象指定为 XMLHttpRequest 对象的 send() 方法的参数值的方法向服务器端发送该 Blob 对象,服务器端接收到该 Blob 对象后将其保存为一个文件,文件名为“副本”+ 当前页面文件的文件名(包括扩展名)。在向服务器端发送 Blob 对象的同时,页面中的进度条将同步显示发送进度。
<script>
window.URL = window.URL || window.webkitURL;
function uploadDocument () {
var bb = new Blob ([document.documentElement.outerHTML]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test.php?fileName='+getFileName(), true);
var progressBar = document.getElementById('progress');
xhr.upload.onprogress = function (e) {
if (e.lengthComputable) {
progressBar.value = (e.loaded / e.total) * 100;
document.getElementById("result").innerHTML='已完成进度:'+progressBar.value+'%';
}
}
xhr.send(bb);
}
function getFileName () { //获取当前页面的文件名
var url = window.location.href;
var pos = url.lastIndexOf("\\");
if (pos == -1) //pos == -1表示为本地文件
pos = url.lastIndexOf("/"); //本地文件路径分割符为“/”
var fileName = url.substring(pos + 1); //从url中获得文件名
return fileName;
}
</script>
<input type="button" value="复制文件" onclick="uploadDocument()"><br/>
<progress min="0" max="100" value="0" id="progress"></progress>
<output id="result">
<?php
$str = file_get_contents('php://input');
$fileName = '副本_'.$REQUEST['fileName'];
$fp = fopen (iconv("UTF-8", "GBK", $fileName), 'w');
fwrite($fp, $str); //插入第一条数据
fclose($fp); //关闭文件
?>
目前,Chrome 浏览器支持在向服务器端发送数据时,同步更新进度条 progress 元素中所显示的进度。
演示效果如下图所示。