【问题标题】:Alamofire download file with progress issue带有进度问题的 Alamofire 下载文件
【发布时间】:2015-12-25 15:50:17
【问题描述】:

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

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.");
}

谁能告诉我我做错了什么?谢谢。

【问题讨论】:

  • 如果服务器返回content-length,请尝试使用一些 REST 客户端。

标签: php ios swift alamofire http-content-length


【解决方案1】:

把代码改成这样解决了:

$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.");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多