delphi調用C#寫的web服務

 

最近一個項目用到了delphi調用C#寫的web服務的功能。用了一天的時間找原因,終於測試通過了。

這是一個通過web服務把一個照片上傳到網站指定位置的方法。先測試了N次都不成功,通過跟蹤發現delphi根本沒傳過來任何值,通過查資料發現VS2005 默認是用的 SoapDocumentProtocol而Delphi 是使用的 SoapRpcProtocol.這會造成所以客戶端傳過去的字符串變

成null,需要在生成的接口單元的INITIALIZATION 部分加上一句:InvRegistry.RegisterInvokeOptions(TypeInfo(ServiceSoap), ioDocument);
搞定了。
服務代碼:

    [WebMethod]
    public int UploadFile(byte[] fs, string FileName)
    {
        try
        {
            ///定義並實例化一個內存流,以存放提交上來的字節數組。
            ///定義實際文件對象,保存上載的文件。
            string FullFilename = Server.MapPath("photo\\") +  FileName;
            if (File.Exists(FullFilename)) { File.Delete(FullFilename); }
            FileStream f = new FileStream(FullFilename, FileMode.Create, FileAccess.Write);
            f.Write(fs, 0, fs.Length);
            f.Close();
            f = null;
            return 1;
        }
        catch
        {
            return 2;
        }
    }
delphi客戶端代碼:

procedure TFrmUpLoad.btn2Click(Sender: TObject);
   function ReadFile(fileName:string): TByteDynArray;
   var
      fs:TFileStream;
     iSize:Int64;
   begin
     try
        fs:=TFileStream.Create(fileName,fmOpenRead);
        iSize:=fs.Seek(0,soFromEnd);
        SetLength(Result,iSize);
        fs.Seek(0,soFromBeginning);
        fs.ReadBuffer(Result[0],iSize);
     finally
        fs.Free;
     end;
   end;
var
  defWSDL,
  defURL,
  defSvc ,
  defPrt :string;
  MyWSUpFile:WSUpFileSoap;
  fs: TByteDynArray;
  fileName:string;
begin
  fs:=ReadFile(edt1.Text);
  defWSDL := 'http://'+sysinfo.WZ+'/wsupfile.asmx?wsdl';
  defURL  := 'http://'+sysinfo.WZ+'/wsupfile.asmx';
  defSvc  := 'WSUpFile';
  defPrt  := 'WSUpFileSoap';
  HTTPRIO1.WSDLLocation:=defWSDL;
  HTTPRIO1.Port:=defPrt;
  HTTPRIO1.URL:=defURL;
  HTTPRIO1.Service:=defSvc;
  HTTPRIO1.HTTPWebNode.UseUTF8InHeader:=true;
  fileName:=HYBH+ExtractFileExt(edt1.Text);
 //注意這一行,可在程序運行中動態改變服務地址,以前俺就不知道這個。

  MyWSUpFile:=GetWSUpFileSoap(True,defWSDL,HTTPRIO1);
  //MyWSUpFile:=HTTPRIO1 as WSUpFileSoap;
  try
    try
     case (MyWSUpFile.UploadFile(fs,fileName)) of
        0:MyShowMessage('用戶無權限');
        1:begin
           FrmHYGL.ADOQuery1.Edit;
           FrmHYGL.ADOQuery1.FieldByName('ZP').AsString:=fileName;
           FrmHYGL.ADOQuery1.Post;
           MyShowMessage('上傳成功');
          end;
        2:MyShowMessage('上傳失敗');
      end;
    finally
      MyWSUpFile:=nil;
    end;
  except
    MyShowMessage('調用web服務失敗!');
  end;
end;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章