[英]Upload a file to web server Delphi + php
i am working on a program and i need to upload a 'log.txt' to a webserver.. by http我正在开发一个程序,我需要通过 http 将“log.txt”上传到网络服务器。
i've searched and got to this :-我已经搜索并找到了这个:-
Delphi XE :德尔福 XE:
procedure TForm1.Button1Click(Sender: TObject);
begin
idhttp1.Post('http://127.0.0.1/GET2.php', 'C:\Users\Someone\Desktop\log.txt')
end;
php :- 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";
}
?>
but no files being uploaded但没有上传文件
thanks for your help感谢您的帮助
Read the PHP documentation.阅读 PHP 文档。
Your PHP code is using $_FILES
, which expects the client to post an HTML webform in MIME multipart/form-data
format:您的 PHP 代码正在使用
$_FILES
,它期望客户端以 MIME multipart/form-data
格式发布 HTML webform:
Handling file uploads > POST method uploads处理文件上传> POST 方法上传
PHP is capable of receiving file uploads from any RFC-1867 compliant browser.
PHP 能够从任何符合RFC-1867 的浏览器接收文件上传。
RFC 1867 Form-based File Upload in HTML RFC 1867 基于表单的 HTML 文件上传
But that format is not what your application is actually posting, though.但是,这种格式并不是您的应用程序实际发布的格式。 It is simply posting the raw file content as-is with no MIME metadata to describe the file.
它只是按原样发布原始文件内容,没有 MIME 元数据来描述文件。 That is why your PHP code is not working.
这就是您的 PHP 代码不起作用的原因。
To post a multipart/form-data
HTML webform using TIdHTTP.Post()
, you have to use the TIdMultipartFormDataStream
class, eg:要使用
TIdHTTP.Post()
发布multipart/form-data
HTML webform,您必须使用TIdMultipartFormDataStream
类,例如:
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;
Alternatively, PHP also supports HTTP PUT
requests for file uploads:或者,PHP 也支持文件上传的 HTTP
PUT
请求:
Handling file uploads > PUT method support处理文件上传> PUT 方法支持
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);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.