Home > Delphi > HTTP Upload File dari Delphi

HTTP Upload File dari Delphi

Delphi Tholos

Image via Wikipedia

Berikut ini function Delphi untuk melakukan upload file menggunakan protokol HTTP. Function ini bisa digunakan pada aplikasi yang memerlukan uploading data ke suatu aplikasi web untuk diproses lebih lanjut, misalnya untuk upload dan import data.

procedure UploadFilesHttpPost(const wb:TWebBrowser; const URLstring: string;
names, values, nFiles, vFiles: array of string) ;
var
  strData, n, v, boundary: string;
 URL: OleVariant;
  Flags: OleVariant;
 PostData: OleVariant;
  Headers: OleVariant;
  idx: Integer;
  ms: TMemoryStream;
  ss: TStringStream;
begin
{
  UploadFilesHttpPost(
  WebBrowser1,
  ‘http://validator.w3.org/check’,
  [],
  [],
  ['uploaded_file'],
  ['C:\blank.htm'] );
}

  if Length(names) <> Length(values) then
    raise Exception.Create(‘UploadFilesHttpPost: Names and Values must have the same length.’) ;
  if Length(nFiles) <> Length(vFiles) then
    raise Exception.Create(‘UploadFilesHttpPost: FileNames and FileValues must have the same length.’) ;
  URL := ‘about:blank’;
  Flags := NavNoHistory or NavNoReadFromCache or NavNoWriteToCache or NavAllowAutosearch;
  wb.Navigate2(URL, Flags) ;
  while wb.ReadyState < READYSTATE_INTERACTIVE
    do Application.ProcessMessages;
  // anything random that WILL NOT occur in the data.
  boundary := ‘—————————123456789′;
  strData := ;
  for idx := Low(names) to High(names) do
  begin
    n := names[idx];
    v := values[idx];
    strData := strData + ‘–’ + boundary + #13#10 +
         ‘Content-Disposition: form-data; name="’ + n + ‘"’ + #13#10#13#10 + v + #13#10;
  end;
  for idx := Low(nFiles) to High(nFiles) do
  begin
    n := nFiles[idx];
    v := vFiles[idx];
    strData := strData + ‘–’ + boundary + #13#10 +
        ‘Content-Disposition: form-data; name="’ + n + ‘"; filename="’ + v + ‘"’ + #13#10;
    if v = then
    begin
       strData := strData + ‘Content-Transfer-Encoding: binary’#13#10#13#10;
    end
    else
    begin
      if (CompareText(ExtractFileExt(v), ‘.JPG’) = 0)
        or (CompareText(ExtractFileExt(v), ‘.JPEG’) = 0) then
      begin
        strData := strData + ‘Content-Type: image/pjpeg’#13#10#13#10;
      end
      else if (CompareText(ExtractFileExt(v), ‘.PNG’) = 0) then
      begin
        strData := strData + ‘Content-Type: image/x-png’#13#10#13#10;
      end
      else if (CompareText(ExtractFileExt(v), ‘.PDF’) = 0) then
      begin
        strData := strData + ‘Content-Type: application/pdf’#13#10#13#10;
      end
      else if (CompareText(ExtractFileExt(v), ‘.HTML’) = 0) then
      begin
      end;
      strData := strData + ‘Content-Type: text/html’#13#10#13#10;
      ms := TMemoryStream.Create;
      try
        ms.LoadFromFile(v) ;
        ss := TStringStream.Create() ;
        try
          ss.CopyFrom(ms, ms.Size) ;
          strData := strData + ss.DataString + #13#10;
        finally
          ss.Free;
        end;
      finally
        ms.Free;
      end;
    end;
    strData := strData + ‘–’ + boundary + ‘–’#13#10; // FOOTER
  end;
  strData := strData + #0;
  {2. you must convert a string into variant array of bytes and every
    character from string is a value in array}

  PostData := VarArrayCreate([0, Length(strData)1], varByte) ;
  { copy the ordinal value of the character into the PostData array}
  for idx := 1 to Length(strData) do PostData[idx-1] := Ord(strData[idx]) ;
  {3. prepare headers which will be sent to remote web-server}
  Headers := ‘Content-Type: multipart/form-data; boundary=’ + boundary + #13#10;
  {4. you must navigate to the URL with your
   script and send as parameters your array with POST-data and headers}

  URL := URLstring;
  wb.Navigate2(URL, Flags, EmptyParam, PostData, Headers) ;
  while wb.ReadyState < READYSTATE_INTERACTIVE do
    Application.ProcessMessages;
end;
 

Terus cara menggunakannya adalah sbb, misal dipanggil pada event click Button1:

procedure TForm1.Button1Click(Sender: TObject);
begin
  UploadFilesHttpPost(
  WebBrowser1,
  ‘http://127.0.0.1/receiver.php’,
  [],
  [],
  [‘uploaded’],
  [‘c:\export.zip’] );
end;
 

Prosedur diatas akan meng-upload file c:\export.zip ke server dengan URL http://127.0.0.1/receiver.php (sebuah script PHP untuk menangani file yang berhasil diupload). Nama field HTML input file upload nya adalah uploaded.

Pada sisi server, script PHP receiver.php yang dipanggil untuk memproses file upload contohnya sbb:

<?
if(move_uploaded_file($_FILES[‘uploaded’][‘tmp_name’], $zipfile))
{
      echo "File $zipfile berhasil diupload";
}
else {
     echo "Sorry, there was a problem uploading your file.";    
}
?>
 

Sumber Delphi.about.com.

Technorati Tags: ,,

Akhmad Daniel Sembiring

vITraining.com – Qualified IT Products, Outsourcing, and Services

Ligarwangi.com – Linux, E-book, Coffee, Gift, etc

Reblog this post [with Zemanta]

  • Share/Bookmark
Categories: Delphi Tags: , ,
  1. aydn
    August 16th, 2010 at 04:08 | #1

    hello ,

    i m sorry but i can not speak german so i will speak english.

    firstly this code is really helpful for my project. but there is something wrong with it. i always take “Sorry, there was a problem uploading your file” error.

    http://127.0.0.1/receiver.php',
    [],
    [],
    ['d:\upload'],
    ['c:\a.zip'] );

    i want to upload c:\a.zip into the d:\upload but i can not. where is the problem ?

  2. August 18th, 2010 at 01:32 | #2

    hi aydn@live.com
    This is Indonesian not German, thanks.
    Please make sure that you have the destination script already ‘http://127.0.0.1/receiver.php’ in this example. You can use any other script if you wish.

  3. aji
    February 14th, 2011 at 16:49 | #3

    mau tanya…
    apakah yang hanya bisa di upload adalah file yang berexistensi (.php)
    bagaimana jika kita ingin mengirimkan file lainnya (.doc, .pdf)
    terima kasih..

  4. February 26th, 2011 at 07:05 | #4

    bisa semua jenis file

  1. No trackbacks yet.
This site uses a Hackadelic PlugIn, Hackadelic SEO Table Of Contents 1.6.0.