12

我的网络服务器上有一个简单的 php 脚本,我需要使用 HTTP POST 上传文件,这是我在 Delphi 中所做的。

这是我在 Indy 上的代码,但显然它不起作用,我无法弄清楚我做错了什么。我如何查看我在服务器上发送的内容是否有这样的工具?

procedure TForm1.btn1Click(Sender: TObject);
var
  fname : string;
  MS,dump : TMemoryStream;
  http  : TIdHTTP;

const
  CRLF = #13#10;
begin
  if PromptForFileName(fname,'','','','',false) then
  begin
    MS := TMemoryStream.Create();
    MS.LoadFromFile(fname);
    dump := TMemoryStream.Create();
    http := TIdHTTP.Create();
    http.Request.ContentType:='multipart/form-data;boundary =-----------------------------7cf87224d2020a';
    fname := CRLF + '-----------------------------7cf87224d2020a' + CRLF + 'Content-Disposition: form-data; name=\"uploadedfile\";filename=\"test.png"' + CRLF;
    dump.Write(fname[1],Length(fname));
    dump.Write(MS.Memory^,MS.Size);
    fname := CRLF + '-----------------------------7cf87224d2020a--' + CRLF;
    dump.Write(fname[1],Length(fname));
    ShowMessage(IntToStr(dump.Size));
    MS.Clear;
    try
    http.Request.Method := 'POST';
    http.Post('http://posttestserver.com/post.php',dump,MS);
    ShowMessage(PAnsiChar(MS.Memory));
    ShowMessage(IntToStr(http.ResponseCode));
    except
    ShowMessage('Could not bind socket');
    end;
  end;
end;
4

3 回答 3

20

Indy has TIdMultipartFormDataStream for this purpose:

procedure TForm1.SendPostData;
var
  Stream: TStringStream;
  Params: TIdMultipartFormDataStream;
begin
  Stream := TStringStream.Create('');
  try
   Params := TIdMultipartFormDataStream.Create;
   try
    Params.AddFile('File1', 'C:\test.txt','application/octet-stream');
    try
     HTTP.Post('http://posttestserver.com/post.php', Params, Stream);
    except
     on E: Exception do
       ShowMessage('Error encountered during POST: ' + E.Message);
    end;
    ShowMessage(Stream.DataString);
   finally
    Params.Free;
   end;
  finally
   Stream.Free;
  end;
end;
于 2012-05-26T11:26:05.950 回答
2

由于用户代理,从 Indy 调用 PHP 可能会失败,然后您会收到 403 错误。

试试这种方式,它为我修复了它:

var Answer: string;
begin
  GetHTML:= TIdHTTP.create(Nil);
  try
    GetHTML.Request.UserAgent:= 'Mozilla/3.0';
    Answer:= GetHTML.Get('http://www.testserver.com/test.php?id=1');
  finally
    GetHTML.Free;
  end;
end;
于 2012-07-31T12:00:15.727 回答
0

您丢失了 2 个字符“--”。最好这样做:

http.Request.ContentType:='multipart/form-data;boundary='+myBoundery;
fname := CRLF + '--' + myBoundery + CRLF + 'Content-Disposition: form-data; name=\"uploadedfile\";filename=\"test.png"' + CRLF;
于 2017-01-27T13:03:59.167 回答