使用delphi以编程方式从下载链接中提取文件名

时间:2010-02-02 12:31:32

标签: delphi

如何使用Delphi从下载链接中提取文件名

实施例

http://pj-mirror01.mozilla.org/pub/mozilla.org/firefox/releases/3.6/win32/es-CL/Firefox%20Setup%203.6.exe

结果必须是

Firefox Setup 3.6.exe

1 个答案:

答案 0 :(得分:5)

试试这个

function GetURLFilename(const FilePath:String;Const Delimiter:String='/'):String;
    var I: Integer;    
begin    
    I := LastDelimiter(Delimiter, FILEPATH);
    Result := Copy(FILEPATH, I + 1, MaxInt);    
    Result := UrlDecode(Result);
end;

URlDecode是从http://www.torry.net/dpfl/dzurl.html复制的,看起来像是

function UrlDecode(const EncodedStr: String): String;
var
  I: Integer;
begin
  Result := '';
  if Length(EncodedStr) > 0 then
  begin
    I := 1;
    while I <= Length(EncodedStr) do
    begin
      if EncodedStr[I] = '%' then
        begin
          Result := Result + Chr(HexToInt(EncodedStr[I+1]
                                       + EncodedStr[I+2]));
          I := Succ(Succ(I));
        end
      else if EncodedStr[I] = '+' then
        Result := Result + ' '
      else
        Result := Result + EncodedStr[I];

      I := Succ(I);
    end;
  end;
end;

function HexToInt(HexStr: String): Int64;
var RetVar : Int64;
    i : byte;
begin
  HexStr := UpperCase(HexStr);
  if HexStr[length(HexStr)] = 'H' then
     Delete(HexStr,length(HexStr),1);
  RetVar := 0;

  for i := 1 to length(HexStr) do begin
      RetVar := RetVar shl 4;
      if HexStr[i] in ['0'..'9'] then
         RetVar := RetVar + (byte(HexStr[i]) - 48)
      else
         if HexStr[i] in ['A'..'F'] then
            RetVar := RetVar + (byte(HexStr[i]) - 55)
         else begin
            Retvar := 0;
            break;
         end;
  end;

  Result := RetVar;
end;