Upload a File to Dropbox
In this post I want to show how easy it is to upload a file to a cloud storage service like Dropbox using the REST components in Delphi XE7.
The API Docs for Dropbox can be found at the link below:
https://www.dropbox.com/developers/core/docs
This post doesn't show how the autorization flow procedure.
Use the following procedure to Upload a File to Dropbox
procedure TForm1.UploadtoCloud(file_path:String);
var
LURL:String;
cloud_path:String;
upload_stream:TFileStream;
begin
//Upload File
addtolog('Direct Upload File');
//root : The root relative to which the path is specified. Valid values are sandbox and dropbox - auto
//path : the path to the file you want to update
local_filename := ExtractFileName(file_path); //Currently extracts file name, and puts in parent folder
cloud_path := local_filename;
//file : Absolute path to the local file you want to upload
local_file_path := file_path;
addtolog(cloud_path);//add to system log
addtolog(local_file_path);//add to system log
//Disable Response Features
RESTResponseDataSetAdapter1.AutoUpdate := false;
//change Request Settings
//https://api-content.dropbox.com/1/
RESTRequest1.Method := TRestRequestMethod.rmPUT;
RESTClient1.BaseURL := 'https://api-content.dropbox.com/1/';
// files_put/auto/<path>?param=val
//Using auto, automatically selects dropbox or sandbox folders
LURL:= 'files_put/auto/'+ URLEncode(cloud_path);
RESTRequest1.Resource := LURL;
//Open File to FileStream
upload_stream := TFileStream.Create(local_file_path,fmOpenRead);
upload_stream.Position := 0;
//Set Content-Type to text/plain
RESTRequest1.Params.AddHeader('Content-Type', 'text/plain');
//Set Request Body to FileStream
RESTRequest1.ClearBody;
RESTRequest1.AddBody(upload_stream,TRESTContentType.ctTEXT_PLAIN);
addtolog(RESTClient1.BaseURL);//add to system log
addtolog(RESTRequest1.Resource);//add to system log
try
//Try Request
RESTRequest1.Execute;
except
on e: Exception do
begin
ShowMessage(e.Message);//Show Exception
addtolog(e.Message);//add to system log
end;
end;
upload_stream.Free; //Free File
end;