之前聽了林壽山老師的課 使用一種新技術 Delphi 撈PHP 資料 回傳json 格式

所以將來的專案 資料要存放在虛擬主機上

但是今天碰到一個問題    上傳檔案 ...

虛擬主機平台只會提供PHP網頁空間

可能會有FTP拉

但是為了一個上傳檔案要在Delphi 寫一堆代碼 太麻煩..

網路上找PHP的 上傳檔案 一定是一堆 用PHP網頁做的

用input標籤 呼叫PHP弄好的檔案上傳功能

但是我這個上傳檔案 是專案的後台

用Excel匯入後 要上傳圖片到網站上

PHP 能不能辦到 匯入Excel的功能 我不是很清楚

但是PHP 上傳檔案 只能用網頁 一個一個 點選檔案 然後在按上傳 也太麻煩了吧

於是找了一整個下午 推測出的PHP檔案上傳的過程

真正抓取檔案資料的 是在<input 標籤裡面 multipart/form-data  <<這個挖溝

而不是由$_File 直接抓檔案資料

所以我原本想用$_POST 直接傳檔案路徑 然後希望PHP直接上傳檔案 是不可能的...?  <<想請PHP神人解答

所以 在呼叫PHP前 就應該準備好檔案資料

幾經波折 找到這一篇

原文網址 : http://stackoverflow.com/questions/33247620/upload-a-file-to-web-server-delphi-php

Delphi 端

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端

<?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);
?>

成功!!!

但是少了一些功能

就是 我要 指定 上傳檔案的檔名

以下是我的代碼

Delphi

procedure TForm1.Button1Click(Sender: TObject);
const url='http://127.0.0.1/file.php?FN=123.txt';
      fn='c:\123.txt';
var fs:Tfilestream;
begin
  fs:=Tfilestream.create(fn,fmOpenRead or fmShareDenyWrite);
  try
    idhttp1.Put(url,fs);//url是文件上传到网站的路径
    showmessage('成功');
  except
    showmessage('失败');
    fs.free;
  end;
end;

PHP端

<?php
if (isset($_GET['FN'])){$FN=$_GET['FN'];}else{$FN='empty';}

/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");

/* Open a file for writing */
$fp = fopen($FN, "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);
?>

 

以上 感謝那個英文網站教學 雖然我大部分都看不懂....

arrow
arrow
    創作者介紹
    創作者 抓狂小白 的頭像
    抓狂小白

    抓狂小白的程式筆記

    抓狂小白 發表在 痞客邦 留言(0) 人氣()