内容长度不在请求中但标题已设置...文件在下载后不会打开

时间:2013-10-24 15:25:40

标签: javascript php download

我有以下代码使用带有进度条的XMLHttpRequest下载文件。

修改

目的是展示千兆速度和普通10 Mbps连接之间的区别。用户在Mac上下载大型视频文件。

页面上显示进度条,文件会在几秒钟内保存到磁盘......然后用户启用硬件切换限制为10Mbps并再次下载,这次肯定会中止330MB文件的传输。

PHP(download.php):

<?
    $file='/path/to/some/video.mp4';

    header('Content-Description: File Transfer');
    header('Content-Type: video/mp4');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($file));
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    ob_clean();
    flush();
    readfile($file);
?>

JavaScript的:

var req = new XMLHttpRequest();
req.onprogress=updateProgress;
req.open('GET', 'download', true);
req.setRequestHeader("Content-Type","video/mp4");
req.onreadystatechange = function (aEvt) {  
    if (req.readyState == 4) {
        ...
    }
};  
req.send();

function updateProgress (evt) {
    console.log(evt);
    var percentComplete = Math.round(evt.loaded * 100 / 330581733);
    $('#downloadProgress').val(percentComplete);
    $('#progressVal').html(percentComplete.toString() + '%');
}

我的请求包含除Content-Length之外的每个标题,当$ filsize被回显时...读取330581733(330MB并进行一些更改)。我的进度函数使用确切的数字进行测试,但应该是evt.total;

第一部分:为什么Content-Length标头不可用?

第二部分:下载完成后,为什么不打开以及它在哪里?

1 个答案:

答案 0 :(得分:0)

我通常不回答我自己的问题但是因为每个人都说这是不可能的,所以我想证明你错了......

首先,您需要从脚本中引用... FileSaver.js

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
window.storageInfo = window.storageInfo || window.webkitStorageInfo;

// Request access to the file system for persistent storage of up to 1GB (1024^3)
navigator.webkitPersistentStorage.requestQuota (1024*1024*1024, function(grantedBytes) {
    console.log ('requestQuota: ', arguments); // FOR DEBUGGING
    window.webkitRequestFileSystem(window.PERSISTENT, grantedBytes, function(fs) {
        console.log ('fs: ', arguments); // FOR DEBUGGING
    }, errorHandler);
}, errorHandler);

req = new XMLHttpRequest(); 
req.onprogress=updateProgress;
req.open('GET', '/path/to/php/download', true);
req.setRequestHeader("Content-Type","video/mp4");
req.responseType = "blob";
req.onreadystatechange = function (aEvt) {  
    if (req.readyState == 4) {
        saveAs(req.response, "filename.mp4"); // DEFINED IN FileSaver.js
    }
}
req.send(null);

// PROGRESS BAR UPDATE
function updateProgress (evt) {
    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
    $('#downloadProgress').val(percentComplete);
} 

这将允许页面上的进度条,并将保存到本地下载目录。

注意:目前仅适用于Chrome。 测试版本:30.0.1599.101(Win 7)

Chrome会在加载带有存储请求的页面时显示一条消息,询问客户端是否正常,将大文件保存到磁盘。

另外值得注意的是Content-Length仍未出现在请求中,并且updateProgress中的evt.total已被静态文件大小替换。