phpSPO
phpSPO copied to clipboard
File is not downloading as content
I tried this file code https://github.com/vgrem/phpSPO/blob/master/examples/SharePoint/DownloadFileAsContent.php but it's not working and throwing me error
PHP Fatal error: Uncaught Office365\Runtime\Http\RequestException: {"error":{"code":"-2147024809, System.ArgumentException","message":{"lang":"en-US","value":"serverRelativeUrl\r\nParameter name: Specified value is not supported for the serverRelativeUrl parameter."}}} in /var/www/html/admin2/vendor/vgrem/php-spo/src/Runtime/ClientRequest.php:213 Stack trace: #0 /var/www/html/admin2/vendor/vgrem/php-spo/src/Runtime/ClientRequest.php(169): Office365\Runtime\ClientRequest->validate(Object(Office365\Runtime\Http\Response)) #1 /var/www/html/admin2/vendor/vgrem/php-spo/src/Runtime/OData/ODataRequest.php(140): Office365\Runtime\ClientRequest->executeQueryDirect(Object(Office365\Runtime\Http\RequestOptions)) #2 /var/www/html/admin2/vendor/vgrem/php-spo/src/Runtime/ClientRuntimeContext.php(119): Office365\Runtime\OData\ODataRequest->executeQueryDirect(Object(Office365\Runtime\Http\RequestOptions)) #3 /var/www/html/admin2/vendor/vgrem/php-spo/src/SharePoint/File.php(200): Office365\Runtime\ClientRuntimeContext->executeQueryDirect(Obje in /var/www/html/admin2/vendor/vgrem/php-spo/src/Runtime/ClientRequest.php on line 213
Hey there. I'm having trouble to make the file downloadable, but I was able to solve your problem.
Imagine you have a folder called "docs" and inside you have the file you want called "file.docx".
$ctx = (new ClientContext("https://your.sharepoint.com/sites"))->withCredentials($credentials);
$sourceFileUrl = '/sites/docs/file.docx';
$fileContent = Office365\SharePoint\File::openBinary($ctx, $sourceFileUrl);
$fileName = join(DIRECTORY_SEPARATOR, [sys_get_temp_dir(), "file.docx"]);
file_put_contents($fileName, $fileContent);
I hope I could help you. Do you know how to download the file after that? Thanks.
PS: I'm not sure if I'm doing everything 100% correct.
To add on to what @fabio-carvalho88 wrote, to make the file downloadable you write the binary stream output to a temporary file, read it and pass it into the buffer while correctly setting headers, and then delete the temporary file afterwards. This will download the file to the user's default download location.
$ctx = (new ClientContext("https://your.sharepoint.com/sites"))->withCredentials($credentials);
$sourceFileUrl = '/sites/docs/file.docx';
$fileContent = Office365\SharePoint\File::openBinary($ctx, $sourceFileUrl);
$fileName = join(DIRECTORY_SEPARATOR, [sys_get_temp_dir(), "file.docx"]);
file_put_contents($fileName, $fileContent);
header( 'Content-type: application/download' );
header( "Content-disposition: attachment; filename=\"$fileName\"" );
fpassthru( fopen( $fileName, 'r' ) );
unlink( $fileName );
Hi @ankursharma1930
I found an error in the project example and I already fixed it #282
Maybe it was this little problem that was giving you error too.