将文件上传到网络服务器 Delphi + php

Upload a file to web server Delphi + php

我正在开发一个程序,我需要将 'log.txt' 上传到网络服务器.. 通过 http

我已经搜索并找到了这个:-

Delphi 谢:

procedure TForm1.Button1Click(Sender: TObject);
begin
idhttp1.Post('http://127.0.0.1/GET2.php', 'C:\Users\Someone\Desktop\log.txt')
end;

php :-

<?php
$uploaddir = "uploads/";
$uploadfile = $uploaddir . basename( $_FILES['file']['name']);

if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile))
{
  echo "The file has been uploaded successfully";
}
else
{
  echo "There was an error uploading the file";
}
?>

但是没有文件上传

感谢您的帮助

阅读 PHP 文档。

您的 PHP 代码正在使用 $_FILES,它希望客户端 post MIME multipart/form-data 格式的 HTML 网络表单:

Handling file uploads > POST method uploads

PHP is capable of receiving file uploads from any RFC-1867 compliant browser.

HTML 中的 RFC 1867 基于表单的文件上传

但是该格式并不是您的应用程序实际 posting 的格式。它只是 post 按原样处理原始文件内容,没有 MIME 元数据来描述文件。这就是为什么您的 PHP 代码不起作用。

要使用 TIdHTTP.Post() post multipart/form-data HTML 网络表单,您必须使用 TIdMultipartFormDataStream class,例如:

uses
  ..., IdHTTP, IdMultipartFormDataStream;

procedure TForm1.Button1Click(Sender: TObject);
var
  PostData: TIdMultipartFormDataStream;
begin
  PostData := TIdMultipartFormDataStream.Create;
  try
    PostData.AddFile('file', 'C:\Users\Someone\Desktop\log.txt');
    idhttp1.Post('http://127.0.0.1/GET2.php', PostData)
  finally
    PostData.Free;
  end;
end;

另外,PHP 也支持 HTTP PUT 文件上传请求:

Handling file uploads > PUT method support

procedure TForm1.Button1Click(Sender: TObject);
var
  FS: TFileStream;
begin
  FS := TFileStream.Create('C:\Users\Someone\Desktop\log.txt', fmOpenRead or fmShareDenyWrite);
  try
    idhttp1.Put('http://127.0.0.1/log.txt', FS);
  finally
    FS.Free;
  end;
end;
<?php
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");

/* Open a file for writing */
$fp = fopen("log.txt", "w");

/* Read the data 1 KB at a time
   and write to the file */
while ($data = fread($putdata, 1024))
  fwrite($fp, $data);

/* Close the streams */
fclose($fp);
fclose($putdata);
?>