0

I want to download a file from server with progress. Here is the code I've tried:

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)
}

But totalBytesExpectedToRead is always -1. I've searched this issue and found that Content-Length on server side isn't set.

I've tried to set it but it doesn't seem to work:

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

Can some one tell me what I'm doing wrong? Thanks.

mkz
  • 2,302
  • 2
  • 30
  • 43

1 Answers1

0

Solved by changing the code to this:

$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.");
}
mkz
  • 2,302
  • 2
  • 30
  • 43