Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to download file as stream from SharePoint with ServerRelativeUrl #284

Closed
la-costa opened this issue Jun 14, 2022 · 2 comments
Closed
Labels

Comments

@la-costa
Copy link
Contributor

I'm having trouble downloading files by stream, maybe because it has a server relative url.

<?php

$siteUrl = "https://organization.sharepoint.com";
$relativeUrl = "/sites/<site-name>";        

$username = "USERNAME";
$password = "PASSWORD";
$credentials = new UserCredentials("{$username}", $password);
$client = (new ClientContext("{$siteUrl}{$relativeUrl}"))->withCredentials($credentials);

$rootFolder = $client
    ->getWeb()
    ->getFolderByServerRelativeUrl('Documents')
    ->expand('Files')
    ->get()
    ->executeQuery()
;

// This works perfectly
print "==> List Files:\r\n";
/** @var File $file */
foreach ($files as $file) {
    print "Filename: {$file->getName()}\r\n";
}

// This works perfectly
print "==> Download as content:\r\n";
foreach ($files as $file) {
    try {
        $sourceFileUrl = "{$relativeUrl}/Documents/{$file->getName()}";
        $fileContent = File::openBinary($client, $sourceFileUrl);
        $fileName = join(DIRECTORY_SEPARATOR, [sys_get_temp_dir(), $file->getName()]);
        file_put_contents($fileName, $fileContent);
        print "Filename: {$file->getName()}\r\n";
    } catch (\Throwable $th) {
        print "Error {$th->getCode()} - File download failed: {$th->getMessage()}";
    }
}        

// This one DOESN'T WORK
print "==> Download as stream:\r\n";
foreach ($files as $file) {
    try {
        $fileName = join(DIRECTORY_SEPARATOR, [sys_get_temp_dir(), $file->getName()]);
        $fh = fopen($fileName, 'w+');
        $file->download($fh);
        $client->executeQuery();
        fclose($fh);
        print "Filename: {$file->getName()}\r\n";
    } catch (\Throwable $th) {
        print "Error {$th->getCode()} - File download failed: {$th->getMessage()}";
    }
}

In the phpSPO project if I comment out the lines of php-spo\src\SharePoint\Web.php the execution works correctly.

public function getResourceUrl()
{
    $url = parent::getResourceUrl();
    // if (!is_null($this->webUrl)) {
    //     return str_replace("/_api/", "{$this->webUrl}/_api/", $url);
    // }
    return $url;
}

What I noticed is that in the current implementation, the server relative url is duplicated.

✔️ Expected: https://organization.sharepoint.com/sites/example/_api/Web/getFileByServerRelativeUrl('%2Fsites%example%2FDocuments%2Ftest.pdf')/$value
❌ Received: https://organization.sharepoint.com/sites/example/sites/example/_api/Web/getFileByServerRelativeUrl('%2Fsites%example%2FDocuments%2Ftest.pdf')/$value

@vgrem vgrem added the bug label Jul 6, 2022
@vgrem
Copy link
Owner

vgrem commented Jul 7, 2022

Greetings,

thank you for catching this error and providing the detailed analysis!
A new version 2.5.4 has been released where among another improvements this issue has been addressed.

@vgrem vgrem closed this as completed Jul 7, 2022
@RajuSysalgo
Copy link

            This code is worked for me 
            
            $sourceFileUrl = '/sites/xyz/Shared Documents/file.jpg';
	$fileContent = File::openBinary($ctx, $sourceFileUrl);
	$fileName = join(DIRECTORY_SEPARATOR, [sys_get_temp_dir(), "sunny.jpg"]);
	print_r($fileName);
	file_put_contents($fileName, $fileContent);

	if (file_exists($fileName)) {
	    header('Content-Description: File Transfer');
	    header('Content-Type: application/octet-stream');
	    header('Content-Disposition: attachment; filename='.basename($fileName));
	    header('Content-Transfer-Encoding: binary');
	    header('Expires: 0');
	    header('Cache-Control: must-revalidate');
	    header('Pragma: public');
	    header('Content-Length: ' . filesize($fileName));
	    ob_clean();
	    flush();
	    readfile($fileName);
	    unlink( $fileName );
	    exit;
	}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants