【问题标题】:Array contents not being passed fully from php client to a .NET web service数组内容未完全从 php 客户端传递到 .NET Web 服务
【发布时间】:2010-06-20 11:17:29
【问题描述】:

我想将图像作为字节数组从 php 传递到 .NET 网络服务。 php客户端如下:

<?php
class Image{
  public $ImgIn = array();
}
$file = file_get_contents('chathura.jpg');
$ImgIn = str_split($file);
foreach ($ImgIn as $key=>$val) { $ImgIn[$key] = ord($val); }

$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage(new Image());
echo $result->PutImageResult;
//print_r($ImgIn);

?>

这是 ASP.NET Web 服务中的 Web 方法:

    [WebMethod]
    public string PutImage(byte[] ImgIn)
    {
        System.IO.MemoryStream ms =
           new System.IO.MemoryStream(ImgIn);
        System.Drawing.Bitmap b =
          (System.Drawing.Bitmap)Image.FromStream(ms);

        b.Save("imageTest", System.Drawing.Imaging.ImageFormat.Jpeg);
        return "test";
    }

当我运行它时,图像内容被正确读取到 php 客户端中的 ImgIm 数组中。 (在本例中,图像有 16992 个元素。)但是,当数组传递给 Web 服务方法时,它只包含 5 个元素(图像的前 5 个元素)
我能知道数据丢失的原因是什么吗?我该如何避免呢?

谢谢

【问题讨论】:

  • 你不应该在 $result = $client->PutImage(new Image()); 行中传递 $ImgIn 而不是 new Image() 吗?
  • 您是否尝试过检查通过网络传输的内容(可能使用 Fiddler 或数据包嗅探器?)
  • @Dan:我已将 ImgIn 声明为 Image 类的属性。因此,当我使用 new Image 时,它​​的所有属性值都被传递。这是传递参数的另一种方式。 @Rowland:我在 web 方法中放置了一个断点并进行了调试。在那里我注意到那里的字节数组只包含 5 个元素。

标签: php asp.net image web-services bytearray


【解决方案1】:

file_get_contents 将文件内容作为字符串返回,这对于图像等二进制文件没有用处。试试这个:

$handle = fopen("chathura.jpg", "r");
$contents = fread($handle, filesize("chathura.jpg"));
fclose($handle);
$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage($contents);

【讨论】:

  • 我尝试了您的代码,但它没有将任何内容传递给 Web 服务。但是考虑到我在 Web 服务中使用的方法,我使用的方法 file_get_contents 是成功的。但问题是整个数组内容没有被传递给 Web 服务。
  • 您的代码也有效。但它有我提到的问题。那不是正在传递数组的全部内容。我认为这可能是由于 php.ini 中数组大小的限制。有什么想法吗?
【解决方案2】:

伙计们,尝试将数据作为字节数组传递似乎没有任何用处,因为 PHP 无论如何都会在发送时将其转换为字符串。这种转换似乎将控制字符引入字符串,使其仅发送字节数组的一部分。我通过发送一个base64编码的字符串并在服务器内部进行解码来实现这一点。 我的客户端代码:

<?php
class Image{
public $ImgIn = '';
}
//ini_set("memory_limit","20M");
$imageData = file_get_contents('chathura.jpg');
$encodedData = base64_encode($imageData);
$Img = new Image();
$Img->ImgIn = $encodedData;
$client = new SoapClient('http://localhost:64226/Service1.asmx?wsdl');
$result = $client->PutImage($Img);
echo($result->PutImageResult);    
?>

ASP .NET 网络服务代码:

    [WebMethod]
    public string PutImage(String ImgIn)
    {
        byte[] ImgInBytes = Convert.FromBase64String(ImgIn);
        System.IO.MemoryStream ms =
           new System.IO.MemoryStream(ImgInBytes);
        System.Drawing.Bitmap b =
          (System.Drawing.Bitmap)Image.FromStream(ms);

        b.Save("C:\\imageTest.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
        return "success";
    }

【讨论】:

    猜你喜欢
    • 2018-06-18
    • 2016-03-16
    • 2011-03-05
    • 2023-03-26
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多