Uploading files to Synology NAS with frpascal code using FileStation API

55 Views Asked by At

I'm playing with a Synology NAS and trying to use its SYNO.FileStation API with freepascal code. All its functions work correctly when I use TFPHTTPClient component GET functions, however when I try to upload a file with POST, I always got an error code:105 which means the logged in session does not have permission.

Beside the syno_token, I also tried to include did and sid values from the the ResponseContent given back by the NAS at the first part of the code, but the result was always the same. My code so far is this:

function TSynologyNAS.UploadFile(const SourceFilePath, DestinationFolder: string): Boolean;
var
  S, synotoken, did, sid: string;
  FormData: TStrings;
  ResponseContent: TStringList;
  Url: string;
  HTTPClient: TFPHTTPClient;
begin
  Result := False;
  


  // Initialize FormData to include the file in the request
  FormData := TStringList.Create;
  try
    FormData.Add('file=' + sourceFilePath); // Assuming simple form data
    // Create an instance of TFPHTTPClient
    HTTPClient := TFPHTTPClient.Create(nil);
    ResponseContent := TStringList.Create;
    HTTPClient.Get(FBaseURL + 'entry.cgi?api=SYNO.API.Auth&version=6&method=login&account=' + FUserName + '&passwd=' + FPassword + '&enable_syno_token=yes', ResponseContent);
    S:= ResponseContent.Text;
    synotoken := Trim(ParseJSONValue(S, 'data.synotoken').AsString);
    did:=  Trim(ParseJSONValue(S, 'data.did').AsString);
    sid:= Trim(ParseJSONValue(S, 'data.sid').AsString);
    // Construct the URL for uploading the file
    Url := FBaseURL + 'entry.cgi?api=SYNO.FileStation.Upload&version=3&method=upload&path=' + HTTPencode(DestinationFolder) +
    '&overwrite=true&filename=' + HTTPEncode(Trim(ExtractFileName(SourceFilePath))) + '&SynoToken=' + synotoken;
    try
      // Perform the file upload using the POST method
      HTTPClient.AddHeader('Authorization', 'Bearer ' + synotoken);
      HTTPClient.FormPost(Url, FormData, ResponseContent);
      Result := True;
    except
      // Handle exceptions if any
      on E: Exception do
      begin
        Result := False;
        ShowMessage('Error: ' + E.Message);
      end;
    end;
  finally
    ResponseContent.Free;
    FormData.Free;
    HTTPClient.Free;
  end;
end;

Is there anyone who has experience with Synology NAS and can give me some advice about this?

0

There are 0 best solutions below