首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用WININET在delphi上上传文件

用WININET在delphi上上传文件
EN

Stack Overflow用户
提问于 2015-11-03 14:53:49
回答 1查看 1.4K关注 0票数 1

我有一个delphi wininet应用程序。

在过去的一周,我试图发送信息来执行JSON方法,本周我试图将一个文件上传到web服务器。我使用相同的代码进行了一些修改,但是在执行InternetWriteFile过程的时候,程序给我带来了一个例外:"Controladorálido“。

守则如下:

代码语言:javascript
运行
复制
    function TFormMain.CargarArchivo(Archivo, Server: string; Username, Password: PChar; blnSSL, iftoken: Boolean): Boolean;
    var
       Url, Header : String;
       pSession, pConnection, pRequest : HINTERNET;
       flags, dwSize, dwFlags : DWORD;
       dwError, Port : Integer;
       Escritos    : Cardinal;
    begin
       Result := false;
       pSession := InternetOpen(nil, INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
       if not Assigned(pSession) then
          raise Exception.Create('InternetOpen failed. ' + WinInetErrorMsg(GetLastError));
       try
          Url := Copy(Server,pos('/Servidor',Server),length(Server));
          if blnSSL then
          begin
             Server := Copy(Server,9,pos('/Servidor',Server)-1);
             Port := INTERNET_DEFAULT_HTTPS_PORT
          end
          else
          begin
             Server := Copy(Server,8,pos('/Servidor',Server)-1);
             Server := Copy(Server,1,pos(':',Server)-1);
             Port := 8080;
          end;
          pConnection := InternetConnect(pSession, PChar(Server), port, Username, Password, INTERNET_SERVICE_HTTP, 0, 0);
          if not Assigned(pConnection) then
             raise Exception.Create('InternetConnect failed. ' + WinInetErrorMsg(GetLastError));
          try
             if blnSSL then
                flags := INTERNET_FLAG_SECURE
             else
                flags := 0;
             pRequest := HTTPOpenRequest(pConnection, 'POST', PChar(Url), nil, nil, nil, flags, 0);
             if not Assigned(pRequest) then
                raise Exception.Create('HttpOpenRequest failed. ' + WinInetErrorMsg(GetLastError));
             try
                // Set buffer size
                dwSize:=SizeOf(dwFlags);
                // Get the current flags
                if (InternetQueryOption(pRequest, INTERNET_OPTION_SECURITY_FLAGS, @dwFlags, dwSize)) then
                begin
                   // Add desired flags
                   dwFlags:=dwFlags or SECURITY_FLAG_IGNORE_UNKNOWN_CA or SECURITY_FLAG_IGNORE_CERT_CN_INVALID or SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
                   // Set new flags
                   if not(InternetSetOption(pRequest, INTERNET_OPTION_SECURITY_FLAGS, @dwFlags, dwSize)) then
                   begin
                      // Get error code
                      dwError:=GetLastError;
                      // Failure
                      MessageBox(Application.Handle, PChar(IntToStr(dwError)), PChar(Application.Title), MB_OK or MB_ICONINFORMATION);
                   end;
                end
                else
                begin
                   // Get error code
                   dwError:=GetLastError;
                   // Failure
                   MessageBox(Application.Handle, PChar(IntToStr(dwError)), PChar(Application.Title), MB_OK or MB_ICONINFORMATION);
                end;
                Header := 'Host: ' + Server + ':' + IntToStr(Port) + #13#10 +
                          'Content-Type: multipart/form-data; charset=UTF-8'#13#10;
                if iftoken then
                begin
                   Header := Header + 'auth_token: '+token+#13#10;
                   Header := Header + 'Csrf-token: no-check'#13#10;
                end;

                if not HttpAddRequestHeaders(pRequest, PChar(Header), Length(Header), HTTP_ADDREQ_FLAG_ADD) then
                   raise Exception.Create('HttpAddRequestHeaders failed. ' + WinInetErrorMsg(GetLastError));

                Parameters := TIdMultiPartFormDataStream.Create;
                Parameters.AddFile('archivo', Archivo, '');
                if not HTTPSendRequest(pRequest, nil, 0, Parameters, Parameters.Size) then
                   raise Exception.Create('HTTPSendRequest failed. ' + WinInetErrorMsg(GetLastError));

                try
                   if not InternetWriteFile(Parameters, Parameters, Parameters.Size, Escritos) then
                      raise Exception.Create('InternetWriteFile failed. ' + WinInetErrorMsg(GetLastError));
                   Result := true;
                finally
                   Parameters.Free;
                end;
             finally
                InternetCloseHandle(pRequest);
             end;
          finally
             InternetCloseHandle(pConnection);
          end;
       finally
          InternetCloseHandle(pSession);
       end;
    end;

我尝试过用FTPOpenFile过程初始化文件指针,但是它不能工作,因为服务器是HTTP,而不是FTP,我想。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-03 15:37:36

你不能把印第和WinInet混在一起,就像你试图混合它们一样。

您正在尝试直接从内存中POST一个独立的TIdMultipartFormDataStream对象。那是行不通的。您必须告诉TIdMultipartFormDataStream从您的输入参数生成它的MIME数据,然后将该数据发布。TIdHTTTP.Post()为您处理这个问题,但是您没有使用TIdHTTP,所以必须手动执行。在这种情况下,您必须将生成的TIdMultipartFormDataStream数据保存到单独的TMemoryStream中(使用TStream.CopyFrom()方法),然后可以使用WinInet发布该数据。

即使如此,您的POST仍然会崩溃,因为:

  1. boundary请求头中不包括所需的Content-Type参数(TIdMultipartFormDataStream动态生成该值),这样服务器就可以正确地解析MIME部分。
  2. 如果HTTPSendRequest()InternetWriteFile()都试图为请求发送正文数据,则不能将它们混合在一起。选一个或另一个。

尝试更像这样的东西:

代码语言:javascript
运行
复制
PostData := TMemoryStream.Create;
try
  Parameters := TIdMultiPartFormDataStream.Create;
  try
    Parameters.AddFile('archivo', Archivo, '');
    PostData.CopyFrom(Parameters, 0);
    Header := 'Host: ' + Server + ':' + IntToStr(Port) + #13#10 +
              'Content-Type: ' + Parameters.RequestContentType + #13#10;
  finally
    Parameters.Free;
  end;    
  if iftoken then
  begin
    Header := Header + 'auth_token: '+token+#13#10;
    Header := Header + 'Csrf-token: no-check'#13#10;
  end;
  if not HttpAddRequestHeaders(pRequest, PChar(Header), Length(Header), HTTP_ADDREQ_FLAG_ADD) then
    raise Exception.Create('HttpAddRequestHeaders failed. ' + WinInetErrorMsg(GetLastError));
  if not HTTPSendRequest(pRequest, nil, 0, PostData.Memory, PostData.Size) then
    raise Exception.Create('HTTPSendRequest failed. ' + WinInetErrorMsg(GetLastError));
  Result := True;
finally
  PostData.Free;
end;
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33502141

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档