Eric Herlitz
Eric Herlitz

Reputation: 26267

Post byte array from PHP to .NET WCF Service

I got a WCF service with a method to receive files, looking something like this

public bool UploadFile(string fileName, byte[] data)
{
   //...
}

What I'd like to do is to post the data to this method in the WCF service from PHP, but are unaware if it's even possible to post byte arrays from PHP to a .NET method hosted by a WCF service.

So I was thinking of something like this

$file = file_get_contents($_FILES['Filedata']['tmp_name']); // get the file content
$client = new SoapClient('http://localhost:8000/service?wsdl');

$params = array(
    'fileName' => 'whatever',
    'data' => $file 
);

$client->UploadFile($params);

Would this be possible or are there any general recommendations out there I should know about?

Upvotes: 6

Views: 4281

Answers (1)

Eric Herlitz
Eric Herlitz

Reputation: 26267

Figured it out. The official php documentation tells that the file_get_contents returns the entire file as a string (http://php.net/manual/en/function.file-get-contents.php). What noone tells is that this string is compatible with the .NET bytearray when posted to a WCF service.

See example below.

$filename = $_FILES["file"]["name"];
$byteArr = file_get_contents($_FILES['file']['tmp_name']);

try {
    $wsdloptions = array(
        'soap_version' => constant('WSDL_SOAP_VERSION'),
        'exceptions' => constant('WSDL_EXCEPTIONS'),
        'trace' => constant('WSDL_TRACE')
    );

    $client = new SoapClient(constant('DEFAULT_WSDL'), $wsdloptions);

    $args = array(
        'file' => $filename,
        'data' => $byteArr
    );


    $uploadFile = $client->UploadFile($args)->UploadFileResult;

    if($uploadFile == 1)
    {
        echo "<h3>Success!</h3>";
        echo "<p>SharePoint received your file!</p>";
    } 
    else
    {
        echo "<h3>Darn!</h3>";
        echo "<p>SharePoint could not receive your file.</p>";
    }


} catch (Exception $exc) {
    echo "<h3>Oh darn, something failed!</h3>";
    echo "<p>$exc->getTraceAsString()</p>";
}

Cheers!

Upvotes: 5

Related Questions