Delphi Dropbox API v2文件上传

时间:2017-06-20 13:03:38

标签: delphi dropbox

我在Delphi 7中使用Dropbox API V2开发了一个Windows桌面软件。 我的代码不起作用。请给我一个正确的考试Delphi代码! 谢谢!

我的代码段:

procedure TDropbox.Upload(SourceFileName: String; DropBoxFileName: String; FTimeout: Integer = 5000);
const
  FDropBoxAppAccessToken = 'xxxxxxxxxxxxxxxxxxxx';    
var    
  FHTTPS: TIdHTTP;    
  FStream: TFileStream;    
  FDropBoxResponseCode: Integer;    
  FHTTPResponse: String;    
begin    
  FHTTPRequestURL := 'https://api-content.dropbox.com/2/files/upload';    
  FStream := TFileStream.Create(SourceFileName, fmOpenRead);    
  FStream.Position := 0;      
  FHTTPS := TIdHTTP.Create(nil);    
  FHTTPS.ConnectTimeout := FTimeout;    
  FDropBoxResponseCode := 0;    
  FHTTPResponse := '';    
  params := TStringList.Create;    
  arg := 'Dropbox-API-Arg:{"path:"' + FDropBoxBaseAppPath + DropBoxFileName + '}';    
  try    
    FHTTPS.Request.CustomHeaders.Add('Authorization:Bearer ' + FDropBoxAppAccessToken);    
    FHTTPS.Request.CustomHeaders.AddStrings := '(Dropbox-API-Arg:{"path:"' + FDropBoxBaseAppPath + DropBoxFileName + '}');    
    FHTTPS.Request.CustomHeaders.Values[arg];    
    FHTTPS.Request.ContentType := 'application/octet-stream';    
    FHTTPS.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(FHTTPS);    
    FHTTPResponse := FHTTPS.Post(FHTTPRequestURL, FStream);    
  except on E: Exception do    
    begin    
    end;    
  end;

Dropbox服务器总是说:

  

400 Bad request,源文件存在。

请帮忙!

1 个答案:

答案 0 :(得分:1)

您正在将请求发送到错误的网址,而您正在滥用Request.CustomHeaders媒体资源,而且您的JSON数据不正确。

尝试更像这样的声音:

procedure TDropbox.Upload(const SourceFileName: String; const DropBoxFileName: String; Timeout: Integer = 5000);
const
  FDropBoxAppAccessToken = 'xxxxxxxxxxxxxxxxxxxx';
  FHTTPRequestURL := 'https://content.dropboxapi.com/2/files/upload';
var
  FHTTPS: TIdHTTP;
  FStream: TFileStream;
  FDropBoxResponseCode: Integer;
  FHTTPResponse: String;
begin
  FDropBoxResponseCode := 0;
  try
    FStream := TFileStream.Create(SourceFileName, fmOpenRead or fmShareDenyWrite);
    try
      FHTTPS := TIdHTTP.Create(nil);
      try
        FHTTPS.ConnectTimeout := Timeout;
        FHTTPS.Request.CustomHeaders.Values['Authorization'] := 'Bearer ' + FDropBoxAppAccessToken;
        FHTTPS.Request.CustomHeaders.Values['Dropbox-API-Arg'] := '{"path": "' + FDropBoxBaseAppPath + DropBoxFileName + '"}';
        FHTTPS.Request.ContentType := 'application/octet-stream';
        FHTTPS.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(FHTTPS);
        FHTTPResponse := FHTTPS.Post(FHTTPRequestURL, FStream);
      finally
        FHTTPS.Free;
      end;
    finally
      FStream.Free;
    end;
  except
    on E: Exception do begin
    end;
  end;
end;