当我使用POST方法时,Indy正在发送空消息

时间:2014-03-14 00:29:52

标签: php delphi indy

我必须使用我的delphi程序上传文件并使用php

处理服务器端

这是我的完整代码:

unit Unit6;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons,
  IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP,
  Vcl.ComCtrls, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack,IdSSLOpenSSL;

type
  TForm6 = class(TForm)
    IdHTTP1: TIdHTTP;
    BitBtn1: TBitBtn;
    od1: TOpenDialog;
    ProgressBar1: TProgressBar;
    m1: TMemo;
    IdIOHandlerStack1: TIdIOHandlerStack;
    procedure BitBtn1Click(Sender: TObject);
    procedure HTTPWorkBegin(Sender: TObject; AWorkMode: TWorkMode;const AWorkCountMax: Integer);
    procedure IdHTTPWork(Sender: TObject; AWorkMode: TWorkMode;const AWorkCount: Integer);
    procedure IdHTTPWorkEnd(Sender: TObject; AWorkMode: TWorkMode);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form6: TForm6;

implementation

{$R *.dfm}

procedure TForm6.HTTPWorkBegin(Sender: TObject; AWorkMode: TWorkMode;
  const AWorkCountMax: Integer);
begin
   if AWorkMode = wmRead then
   begin
      ProgressBar1.Max := AWorkCountMax;
      ProgressBar1.Position := 0;
   end;
end;

procedure TForm6.IdHTTPWork(Sender: TObject; AWorkMode: TWorkMode;
  const AWorkCount: Integer);
begin
   if AWorkMode=wmRead then
     ProgressBar1.Position := AWorkCount;
end;


procedure TForm6.IdHTTPWorkEnd(Sender: TObject; AWorkMode: TWorkMode);
begin
  ProgressBar1.Position := 0;
end;

procedure TForm6.BitBtn1Click(Sender: TObject);
var
 Response:string;
   LHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
  if od1.Execute then
  begin
 //   LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
   // IdHTTP1.IOHandler:=LHandler;
    Response := IdHTTP1.Post('http://localhost/delphi/index.php?asd', od1.FileName);
    m1.Text := Response;
  end;
end;

end.

服务器端在php:

test1
<?php
    print_r($_FILES);
?>

我也改为:

test1
<?php
    print_r($_POST);
?>

但是在所有测试中,delphi响应都是一个空数组。

test1
Array
(
)

我的代码的哪一部分是问题?!

1 个答案:

答案 0 :(得分:2)

您正在将文件名传递给TIdHTTP.Post()。即按原样发布文件的原始内容。这不会填充PHP的$_FILES数组(用于multipart/form-data帖子)或$_POST数组(用于application/x-www-form-urlencoded帖子)。

将文件添加到TIdMultipartFormDataStream并将其发布。它将发送一个应填充multipart/form-data数组的$_FILES帖子,例如:

uses
  ..., IdMultipartFormData;

procedure TForm6.BitBtn1Click(Sender: TObject);
var
  //LHandler: TIdSSLIOHandlerSocketOpenSSL;
  PostData: TIdMultipartFormDataStream;
begin
  if od1.Execute then
  begin
    //LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
    //IdHTTP1.IOHandler := LHandler;

    PostData := TIdMultipartFormDataStream.Create;
    try
      PostData.AddFile('file', od1.FileName);
      m1.Text := IdHTTP1.Post('http://localhost/delphi/index.php?asd', PostData);
    finally
      PostData.Free;
    end;
  end;
end;