我必须使用我的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
(
)
我的代码的哪一部分是问题?!
答案 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;