php - Alamofire 下载文件存在进度问题

标签 php ios swift alamofire http-content-length

我想从服务器下载一个有进度的文件。这是我尝试过的代码:

let destination: (NSURL, NSHTTPURLResponse) -> (NSURL) = {
    (temporaryURL, response) in
    if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
        let path = directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
        return path
    }
    return temporaryURL
}

Alamofire.download(.GET, fileUrls[button.tag], destination: destination)
.progress { _, totalBytesRead, totalBytesExpectedToRead in
    dispatch_async(dispatch_get_main_queue()) {
        println("\(Float(totalBytesRead)) - \(Float(totalBytesExpectedToRead))")

        if totalBytesRead == totalBytesExpectedToRead {
            println("******************************")
            println("finished")
            println("******************************")
        }
    }
}
.response { (_, _, data, error) in
    println(data)
    println(error)
}

但是totalBytesExpectedToRead始终为-1。我搜索了这个问题,发现服务器端的Content-Length没有设置。

我尝试过设置,但似乎不起作用:

$attachment_location = $_GET["filepath"];
if (file_exists($attachment_location)) {
    header('Content-Description: File Transfer');
    header('Content-Type:' . mime_content_type($attachment_location));
    header('Content-Disposition: attachment; filename='.basename($attachment_location));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($attachment_location));
    readfile($attachment_location);
    die(); 
} else {
    die("Error: File not found.");
}

有人可以告诉我我做错了什么吗?谢谢。

最佳答案

通过将代码更改为以下内容来解决:

$attachment_location = $_GET["filepath"];
if (file_exists($attachment_location)) {
    header('Content-Description: File Transfer');
    header('Content-Type:' . mime_content_type($attachment_location));
    header('Content-Disposition: attachment; filename='.basename($attachment_location));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Encoding: chunked');
    header('Content-Length: ' . filesize($attachment_location), true);
    readfile($attachment_location);
    die(); 
} else {
    die("Error: File not found.");
}

关于php - Alamofire 下载文件存在进度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32822394/

相关文章:

php - 尝试读取文件时页面未加载

ios - 如何让 DTCoreText 使用系统字体?

iphone - 将部分 mySQL DB 从网站转换为 iOS 上的 CoreData/SQLite

swift - 了解 Realm 中的迁移 - Swift

ios - 为什么 buttonName.removeFromSuperview 不总是删除按钮?

php - 关于 PHP 语法错误的 Apache 内部错误 500 (htaccess)

php - PSR-4 自动加载问题

php - 如何在 WAMP 中用 MariaDb 替换 MySql?

android - 需要在 iOS 中安装第二个应用程序

tableview - Xcode 6 + Swift 中的自定义单元格不显示