Dropbox: Produce a direct download link [PHP preferred]

我们两清 提交于 2019-11-28 20:57:12
Paul

It turns out that the default share url that is returned is a short url and the short url will always point to the Dropbox preview page.

Therefore, you need to get the REST API to return the full url by setting the short_url parameter to false. Once you have the full url, then add ?dl=1 at the end of url.

Eg: https://dl.dropbox.com/s/xxxxxxxxxxxxxxxxxx/MyFile.pdf?dl=1

More info:

https://www.dropbox.com/help/201/en

Prompt user to save on download from Dropbox

PHP Example:

This example has borrowed/inspired-by code samples from these: http://www.phpriot.com/articles/download-with-curl-and-php

http://www.humaan.com.au/php-and-the-dropbox-api/

/* These variables need to be defined */
$app_key = 'xxxxxxxx';
$app_secret = 'xxxxxxxxxxxxxxxxxxxx';
$user_oauth_access_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$user_oauth_access_token_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';    

$ch = curl_init(); 

$headers = array( 'Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT"' );

$params = array('short_url' => 'false', 'oauth_consumer_key' => $app_key, 'oauth_token' => $user_oauth_access_token, 'oauth_signature' => $app_secret.'&'.$user_oauth_access_token_secret);

curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $params);
curl_setopt( $ch, CURLOPT_URL, 'https://api.dropbox.com/1/shares/'.$dir );

/*
* To handle Dropbox's requirement for https requests, follow this:
* http://artur.ejsmont.org/blog/content/how-to-properly-secure-remote-api-calls-from-php-application
*/
curl_setopt( $ch, CURLOPT_CAINFO,getcwd() . "\dropboxphp\cacert.pem");
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, TRUE);

curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE );
$api_response = curl_exec($ch);

if(curl_exec($ch) === false) {
    echo 'Curl error: ' . curl_error($ch);
}

$json_response = json_decode($api_response, true);

/* Finally end with the download link */
$download_url = $json_response['url'].'?dl=1';
echo '<a href="'.$download_url.'">Download me</a>';

Folks looking for a similar solution to get a direct link to download a file that skips the Dropbox download window can use the "Get Temporary Link" endpoint added in version 2 of the API.

https://www.dropbox.com/developers/documentation/http/documentation#files-get_temporary_link

Get a temporary link to stream content of a file. This link will expire in four hours and afterwards you will get 410 Gone. Content-Type of the link is determined automatically by the file's mime type.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!