Новичок
Профиль
Группа: Участник
Сообщений: 1
Регистрация: 23.12.2010
Репутация: нет Всего: нет
|
Добрый день!!! Очень нужно отправить файл на сервер так же как и отправляется из формы. Пример кода следующий: Код | <html> <head> </head> <body> <form method="post" enctype="multipart/form-data" action="http://someserver/path/script.php?param1=sometext"> <input type="hidden" name="param2" value="sometext"> <input type="hidden" name="param3" value="sometext"> <input type="file" name="myfile" value="">
<input type="submit" value="Download"> </form> </body> </html>
|
Из браузера отправляется все нормально, а из код ниже нет: Код | unit Unit1;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, StdCtrls, WinInet;
type TForm1 = class(TForm) Edit1: TEdit; Button1: TButton; SpeedButton1: TSpeedButton; OpenDialog1: TOpenDialog; Memo1: TMemo; procedure Button1Click(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure Edit1Change(Sender: TObject); private { Private declarations } public { Public declarations } end;
TRequestOptions = array of record Name: String; Value: String; RecType: String; end;
TRequestInfo = record Headers: String; Host: String; Script: String; Connection: Cardinal; Request: Cardinal; AccessType: String; end;
var Form1: TForm1;
const MozillaFireFox: PAnsiChar = PAnsiChar('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)'); InternetExplorer6: PAnsiChar = PAnsiChar('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)');
implementation
{$R *.dfm}
function UploadFile(ARequest: String; AOptions: TRequestOptions; AMethod: String; AContentType: String; out Response: AnsiString): Boolean; stdcall; var Info: TRequestInfo; Params: String; Internet: hInternet; Connection: hInternet; Request: hInternet; Count, Readed, Size, Index: Cardinal; Headers: TStringList; Contents: String; OutString: PAnsiChar;
function EncodeParams(AParams: TRequestOptions): String; var i: Integer; begin Result := '';
if Length(AParams) > 0 then begin for i := 0 to Length(AParams) - 1 do begin if Result <> '' then Result := Result + '&' + AParams[i].Name + '=' + AParams[i].Value else Result := Result + AParams[i].Name + '=' + AParams[i].Value; end; end; end;
function GetHostName : String; var Protocol: String; URI: String; begin Result := ''; URI := ARequest;
if Pos('https://', URI) > 0 then Protocol := 'https://' else if Pos('http://', URI) > 0 then Protocol := 'http://' else Protocol := '';
if Protocol <> '' then begin Delete(URI, 1, Length(Protocol)); SetLength(URI, Pos('/', URI) - 1); Result := URI; end; end;
function GetScriptName(AHostName: String): String; var URI: String; begin URI := ARequest;
Result := ''; Delete(URI, 1, Pos(AHostName, URI) + Length(AHostName) - 1); Result := URI; end;
procedure SetFlags(out Flags_Connection, Flags_Request : Cardinal); begin if Pos('https', ARequest) > 0 then begin Flags_Connection := INTERNET_DEFAULT_HTTPS_PORT; Flags_Request := INTERNET_FLAG_RELOAD or INTERNET_FLAG_IGNORE_CERT_CN_INVALID or INTERNET_FLAG_NO_CACHE_WRITE or INTERNET_FLAG_SECURE or INTERNET_FLAG_PRAGMA_NOCACHE or INTERNET_FLAG_KEEP_CONNECTION; end else begin Flags_Connection := INTERNET_DEFAULT_HTTP_PORT; Flags_Request := INTERNET_FLAG_RELOAD or INTERNET_FLAG_IGNORE_CERT_CN_INVALID or INTERNET_FLAG_NO_CACHE_WRITE or INTERNET_FLAG_PRAGMA_NOCACHE or INTERNET_FLAG_KEEP_CONNECTION; end; end;
function GetFileContents(AFileName: String): PAnsiChar; var f: file of Char; begin Result := '';
if FileExists(AFileName) then begin AssignFile(f, AFileName); Reset(f);
BlockRead(f, Result, FileSize(f));
CloseFile(f); end; end;
function GetContents(Boundary: String): String; var i: Integer; begin Result := '';
if Length(AOptions) > 0 then begin for i := 0 to Length(AOptions) - 1 do begin if AOptions[i].RecType = 'text' then begin Result := Result + '--' + Boundary + ''#10#13'' + 'Content-Disposition: form-data; name="' + AOptions[i].Name + '"'#10#13#10#13'' + AOptions[i].Value + ''#10#13''; end else if AOptions[i].RecType = 'file' then begin Result := Result + '--' + Boundary + ''#10#13'' + 'Content-Disposition: form-data; name="' + AOptions[i].Name + '"; filename="' + AOptions[i].Value + '"'#10#13''; Result := Result + 'Content-type: application/octet-stream'#10#13#10#13''; Result := Result + 'TestFile'#10#13''; end; end; end;
Result := Result + '--' + Boundary + '--'; end;
begin Response := ''; Result := True;
Params := EncodeParams(AOptions);
info.Host := GetHostName; info.Script := GetScriptName(info.Host); info.AccessType := 'Content-Type: multipart/form-data'#10#13'Content-Length:' + IntToStr(Length(Params));
Contents := GetContents('ATTRIBUTES');
SetFlags(info.Connection, info.Request);
Headers := TStringList.Create;
Headers.Add('Accept: */*'); Headers.Add('Accept-Language: ru'); Headers.Add('Content-Type: multipart/form-data; boundary=ATTRIBUTES'); Headers.Add('Accept-Encoding: gzip, deflate'); Headers.Add('User-Agent: ' + MozillaFireFox); Headers.Add('Host: ' + info.Host); Headers.Add('Connection: Keep-Alive'); Headers.Add('Cache-Control: no-cache'); Headers.Add('Content-Length: ' + IntToStr(Length(Contents)) + ''#10#13'');
ShowMessage(Headers.Text + Contents);
Internet := InternetOpen(MozillaFireFox, INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if Assigned(Internet) then begin Connection := InternetConnect(Internet, PAnsiChar(info.Host), info.Connection, nil, nil, INTERNET_SERVICE_HTTP, 0, 1);
if Assigned(Connection) then begin Request := HTTPOpenRequest(Connection, PAnsiChar(UpperCase(AMethod)), PAnsiChar(info.Script), HTTP_VERSION, nil, nil, info.Request or INTERNET_FLAG_KEEP_CONNECTION, 1);
if Assigned(Request) then begin Count := 1;
ShowMessage('Sending data');
if HTTPSendRequest(Request, PAnsiChar(Headers.Text), Length(Headers.Text), PAnsiChar(Contents), Length(Contents)) then begin Index := 0;
if HTTPQueryInfo(Request, HTTP_QUERY_RAW_HEADERS_CRLF, OutString, Readed, Index) = False then begin ShowMessage(IntToStr(GetLastError));
if GetLastError = ERROR_INSUFFICIENT_BUFFER then begin SetLength(OutString, Readed);
HTTPQueryInfo(Request, HTTP_QUERY_RAW_HEADERS_CRLF, OutString, Readed, Index); end; end else begin Form1.Memo1.Clear;
Form1.Memo1.Text := OutString; end;
ShowMessage('Sended'); end;
InternetCloseHandle(Request); end;
InternetCloseHandle(Connection); end;
InternetCloseHandle(Internet); end;
ShowMessage(info.Host + ''#10#13'' + info.Script); end;
procedure TForm1.Button1Click(Sender: TObject); var Options: TRequestOptions; begin SetLength(Options, 3);
Options[0].Name := 'param2'; Options[0].Value := 'sometext'; Options[0].RecType := 'text';
Options[1].Name := 'param3'; Options[1].Value := 'sometext'; Options[1].RecType := 'text';
Options[2].Name := 'myfile'; Options[2].Value := OpenDialog1.FileName; Options[2].RecType := 'file';
UploadFile('http://someserver/path/script.php?param1=sometext', Options, 'post', 'application/form-data', Content); end;
procedure TForm1.SpeedButton1Click(Sender: TObject); begin if OpenDialog1.Execute then Edit1.Text := OpenDialog1.FileName; end;
procedure TForm1.Edit1Change(Sender: TObject); begin if Edit1.Text = '' then Button1.Enabled := False else Button1.Enabled := True; end;
end.
|
На сервер от браузера отправляется следующее: Код | POST /path/script.php?param1=sometext HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/pdf, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */* Accept-Language: ru Content-Type: multipart/form-data; boundary=---------------------------7dacb98007c6 Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729) Host: someserver Content-Length: 891285 Connection: Keep-Alive Cache-Control: no-cache Cookie: name=value
-----------------------------7dacb98007c6 Content-Disposition: form-data; name="param2"
sometext -----------------------------7dacb98007c6 Content-Disposition: form-data; name="param3"
sometext -----------------------------7dacb98007c6 Content-Disposition: form-data; name="myfile"; filename="C:\file.rar" Content-Type: application/octet-stream
Rar! -----------------------------7dacb98007c6--
|
В ответ приходит такое: Код | HTTP/1.1 200 OK Server: nginx/0.7.65 Date: Fri, 24 Dec 2010 12:05:34 GMT Content-Type: text/html Transfer-Encoding: chunked Connection: close X-Powered-By: PHP/5.2.12 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache
<!DOCTYPE HTML PUBLIC "-//W3C//Dtd HTML 4.01 transitional//EN"> <html> <body> </body> </html>
|
Файл загружен на сервер без проблем. Но делаю примерно тоже, а результат совсем иной!!! Большая просьба, помогите разобраться!!! Очень срочно!!! ТОЛЬКО WININET!!!
|