Your workflow is unique 👨💻 - tell us how you use Dropbox here.
Download
8 TopicsUsing API and SDK together
Hello, I need some help until now i have been using >NET SDK Version 6.37. and we are experiencing a problem downloading large files 30GB and higher. so I tried to implement chunk download, but SDK does not support it . so I did it using the API. but my problem is that when we use the SDK we do not Need to refresh token. and when we use api after some time I am getting 401 . so I implemented a refresh token method, and refreshed the token , but still after sending the request again with the new token I got I am still getting the 401. I tried to get the token from the Dropbox Client but it is not there also regarding the refresh token , is this token always stays the same ? can some one help? adding some code snipped. public async Task<string> RefreshAccessTokenAsync(string expiredAccessToken,BaseRequest baserRequest,bool isBusinessClient, CancellationToken token) { using (var http = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, "https://api.dropboxapi.com/oauth2/token"); var content = new FormUrlEncodedContent(new Dictionary<string, string> { { "grant_type", "refresh_token" }, { "refresh_token", baserRequest.RefreshToken }, { "client_id", isBusinessClient ?ClientIdBusiness : ClientId }, { "client_secret", isBusinessClient ? ClientSecretBusiness : ClientSecret } }); request.Content = content; using (var response = await http.SendAsync(request, token)) { response.EnsureSuccessStatusCode(); var json = await response.Content.ReadAsStringAsync(); dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(json); string newAccessToken = result.access_token; if (string.IsNullOrEmpty(newAccessToken)) throw new Exception("Dropbox token refresh failed: access_token not returned."); return newAccessToken; } } } private async Task DownloadFileInChunksHttpAsync( string accessToken, string dropboxPath, string localPath, long fileSize, string asMember, string rootNamespaceId, CancellationToken token, BaseRequest baseRequest, bool isBusinessClient) // <-- tells refresh which client to use { DropboxTeamClient client; const int bufferSize = 1024 * 1024; // 1MB const long chunkSize = 50L * 1024 * 1024; // 50MB using (var fileStream = new FileStream(localPath, FileMode.Create, FileAccess.Write, FileShare.None)) using (var http = new HttpClient()) { string currentAccessToken = accessToken; long offset = 0; while (offset < fileSize) { long end = Math.Min(offset + chunkSize - 1, fileSize - 1); bool retriedAfterRefresh = false; RetryChunk: var request = new HttpRequestMessage(HttpMethod.Post, "https://content.dropboxapi.com/2/files/download"); // Authorization request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", currentAccessToken); // Dropbox-API-Arg (JSON-encoded) var arg = new { path = dropboxPath }; string jsonArg = Newtonsoft.Json.JsonConvert.SerializeObject(arg); request.Headers.Add("Dropbox-API-Arg", jsonArg); // Range header for chunking request.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(offset, end); // Act as team member (Business) if (!string.IsNullOrEmpty(asMember)) request.Headers.Add("Dropbox-API-Select-User", asMember); // Apply PathRoot (WithPathRoot) for Business only if (!string.IsNullOrEmpty(rootNamespaceId)) { var pathRoot = new Dictionary<string, object> { { ".tag", "root" }, { "root", rootNamespaceId } }; string jsonPathRoot = Newtonsoft.Json.JsonConvert.SerializeObject(pathRoot); request.Headers.Add("Dropbox-API-Path-Root", jsonPathRoot); } using (var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token)) { // 🔐 Handle expired token (401) if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { if (retriedAfterRefresh) { var err = await response.Content.ReadAsStringAsync(); throw new HttpRequestException( $"Dropbox download failed after token refresh (401). Body: {err}"); } // Refresh token based on client type (Personal vs Business) currentAccessToken = await RefreshAccessTokenAsync(currentAccessToken, baseRequest, isBusinessClient, token).ConfigureAwait(false); retriedAfterRefresh = true; goto RetryChunk; } // ❌ Other errors if (!response.IsSuccessStatusCode) { var err = await response.Content.ReadAsStringAsync(); throw new HttpRequestException( $"Dropbox download failed: {(int)response.StatusCode} {response.ReasonPhrase}. Body: {err}"); } // ✅ Success using (var stream = await response.Content.ReadAsStreamAsync()) { fileStream.Seek(offset, SeekOrigin.Begin); await stream.CopyToAsync(fileStream, bufferSize, token); } } offset = end + 1; } } } public async Task<DownloadFileResponse> DownloadFileAsync(DownloadFileRequest request) { DropboxTeamClient client; var connectionId = GetDropboxTeamClient(request, out client); ////logsfodebug(request, "DownloadFileAsync"); var account = await client.AsMember(request.AsMember).Users.GetCurrentAccountAsync(); var spaceclient = client.AsMember(request.AsMember).WithPathRoot(new PathRoot.Root(account.RootInfo.RootNamespaceId)); bool newTeam = CheckIfUserIsUpdatedTeam(account); string tempFilename; if (request.ExportAs != null) { // ===== EXPORT: REVERTED TO OLD SDK CODE (AS REQUESTED) ===== tempFilename = await Retries.PerformWithRetriesAsync( async () => { var path = request.FilePath.Replace('\\', '/'); var fileInfo = await spaceclient.Files.GetMetadataAsync(path) .ConfigureAwait(false); if (fileInfo.IsDeleted) throw new CannotDownloadFileException(string.Format("File was Deleted. - {0}", path)); long? size = request.Size ?? (long)fileInfo.AsFile.Size; using (var safeTemporaryFileProvider = new SafeTemporaryFileProvider(() => PathExtensions.GetTempFileName(request.ContextId))) { using (var tokenSource = new CancellationTokenSource(TimeoutHelper.FromSize(size))) { // OLD SDK EXPORT CODE (unchanged) using (var downloadResponse = await spaceclient.Files .ExportAsync(new ExportArg(request.FilePath, null)) .WithCancellation(tokenSource.Token).ConfigureAwait(false)) { using (var fileStream = new FileStream(safeTemporaryFileProvider.TempFilename, FileMode.Create)) { var downloadStream = await downloadResponse.GetContentAsStreamAsync() .WithCancellation(tokenSource.Token) .ConfigureAwait(false); await downloadStream.CopyToAsync(fileStream, 4096, tokenSource.Token) .WithCancellation(tokenSource.Token) .ConfigureAwait(false); return safeTemporaryFileProvider.TempFilename; } } } } }, ShouldRetryWithDelay).ConfigureAwait(false); } else { if (newTeam) { // ===== BUSINESS / TEAM: NEW HTTP CHUNKED DOWNLOAD ===== tempFilename = await Retries.PerformWithRetriesAsync( async () => { var path = request.FilePath.Replace('\\', '/'); var fileInfo = await spaceclient.Files.GetMetadataAsync(path).ConfigureAwait(false); if (fileInfo.IsDeleted) throw new CannotDownloadFileException(string.Format("File was Deleted. - {0}", path)); long? size = request.Size ?? (long)fileInfo.AsFile.Size; using (var safeTemporaryFileProvider = new SafeTemporaryFileProvider(() => PathExtensions.GetTempFileName(request.ContextId))) { using (var tokenSource = new CancellationTokenSource(TimeoutHelper.FromSize(size))) { await DownloadFileInChunksHttpAsync( request.AccessToken, path, safeTemporaryFileProvider.TempFilename, size ?? 0, request.AsMember, account.RootInfo.RootNamespaceId, tokenSource.Token, request, true); // <-- Business client return safeTemporaryFileProvider.TempFilename; } } }, ShouldRetryWithDelay).ConfigureAwait(false); } else { // ===== PERSONAL: NEW HTTP CHUNKED DOWNLOAD ===== tempFilename = await Retries.PerformWithRetriesAsync( async () => { var path = request.FilePath.Replace('\\', '/'); var fileInfo = await client.AsMember(request.AsMember).Files.GetMetadataAsync(path).ConfigureAwait(false); if (fileInfo.IsDeleted) throw new CannotDownloadFileException(string.Format("File was Deleted. - {0}", path)); long? size = request.Size ?? (long)fileInfo.AsFile.Size; using (var safeTemporaryFileProvider = new SafeTemporaryFileProvider(() => PathExtensions.GetTempFileName(request.ContextId))) { using (var tokenSource = new CancellationTokenSource(TimeoutHelper.FromSize(size))) { await DownloadFileInChunksHttpAsync( request.AccessToken, path, safeTemporaryFileProvider.TempFilename, size ?? 0, request.AsMember, null, tokenSource.Token, request, false); // <-- Personal client return safeTemporaryFileProvider.TempFilename; } } }, ShouldRetryWithDelay).ConfigureAwait(false); } } var response = new DownloadFileResponse { LocalPath = tempFilename }; return UpdateTokens(response, request, client, connectionId); }161Views0likes7CommentsDirect download using android java
Until recently my android app was able to download txt files from my dropbox account using this dl.dropboxusercontent.com/s/bbbejnmpch8fve1/lastsequence.txt?dl=0 However I now get java.io.FileNotFoundException If I log in using a web browser I can see the file is still there and can be download via the browser fine. What has changes that is stopping the above url from fetching the file. Perhaps the service has changed. I have the basic free account which has served me well since 2016 for this function. I am not using the API but android java Http and was getting the contents from the returned resonse using getinputstream. How it returns file not found. Any help or advice would be helpful, thanks.Solved403Views0likes3CommentsSlow response using Dropbox for Python
Hello, My python code has been working well for months. Within the past 48 hours, the files_download command in the snippet below (with tokens obfuscated) has started to take about 45 seconds while previously it was instantaneous. It is the last line that is the culprit. import dropbox DROPBOX_APP_KEY = "?????" DROPBOX_APP_SECRET = "?????" DROPBOX_REFRESH_TOKEN = "????" dbx = dropbox.Dropbox(app_key=DROPBOX_APP_KEY, app_secret=DROPBOX_APP_SECRET, oauth2_refresh_token=DROPBOX_REFRESH_TOKEN) metadata, f = dbx.files_download('/alerts.csv') Any suggestions? With thanks, David328Views0likes6CommentsError reading file async
I had a problem to download a file ( an Image ) and someone recommended to me to do asynchronously. I changed my code so : Async Function _take_file(ByVal _file As String) As Task .... Dim client As HttpClient = New HttpClient() Dim _Request As HttpRequestMessage = New HttpRequestMessage(HttpMethod.Post, "https://content.dropboxapi.com/2/files/download") _Request.Headers.Add("Authorization", "Bearer " + _token) _Request.Headers.Add("Dropbox-API-Arg", _parametro) Dim _response As HttpResponseMessage = Await client.SendAsync(_Request) Dim _responseStream As Stream = Await _response.Content.ReadAsStreamAsync() Dim myStreamReader As New StreamReader(_responseStream) I have an error on the last line : System.NullReferenceException was unhandled Message: An unhandled exception of type 'System.NullReferenceException' occurred in mscorlib.dll920Views0likes11CommentsDownload file by Api ( Files/download ) , no error no file
I try to dowload a file by a Api . I have no error and a response with "OK" but i don't see the file. Have i donwloaded it ? where ? can i set up the local directory where save it ? This is my code : ( a big doubt is in content-Type ) Dim _command As String _command = "https://content.dropboxapi.com/2/files/download" Dim Request As HttpWebRequest Request = HttpWebRequest.Create(_command) Request.Method = "POST" Request.KeepAlive = True ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 Or SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls Request.ContentType = "application/octet-stream" Request.UserAgent = "Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36" ServicePointManager.SecurityProtocol = CType(48, SecurityProtocolType) Or CType(192, SecurityProtocolType) Or CType(768, SecurityProtocolType) Or CType(3072, SecurityProtocolType) Request.AllowAutoRedirect = True Request.Headers.Add("Authorization", "Bearer " & _token) Request.Headers.Add("Dropbox-API-Arg", _parameter) Try Dim Response As HttpWebResponse = Request.GetResponse() Catch ex As WebException Using response = CType(ex.Response, HttpWebResponse) Using reader = New IO.StreamReader(response.GetResponseStream()) _error = reader.ReadToEnd() End Using End Using Catch ex As Exception Throw End Try350Views0likes1CommentI can't download files by command
Download files with wget Hello gentlemen of the community. I have a problem. I've been using "wget" since June 2021 to download a file and since then everything has been fine. But this morning the command does not respond and gives clues as to what may be happening. Below is the command I use and it was working: wget -q --no-check-certificate https://www.dropbox.com/s/4mf0awazg0z0ols/TESTE.7z -O TESTE.7z It simply skips a line without any message. I thank you in advance for your support. Marcos4.1KViews0likes9Comments