phpSPO icon indicating copy to clipboard operation
phpSPO copied to clipboard

How can i get a specific file by file name?

Open Rain-YuXia opened this issue 3 years ago • 3 comments

I generate a word docx and upload to sharepoint, which is working amazing.

After that, I would like to get this uploaded docx. Is there any way to do this? Please help.

At the moment I have to get all files in the folder and loop through to find the docx I want...

Rain-YuXia avatar May 19 '21 05:05 Rain-YuXia

If you know the path and filename, you could do this:

$ctx = ClientContext::connectWithClientCredentials($url, $client_id, $client_secret); // connect
$server_relative_path = " /sites/Folder/SubFolder/Filename.docx"; // the file you want to get
$targetFile = $ctx->getWeb()->getFileByServerRelativePath(new SPResourcePath($server_relative_path)); // get the file
$targetFile->getUniqueId(); // do something with the file

Not sure if that helps, hope it does.

the things you can do with a File

coda1024 avatar May 20 '21 01:05 coda1024

If you know the path and filename, you could do this:

$ctx = ClientContext::connectWithClientCredentials($url, $client_id, $client_secret); // connect
$server_relative_path = " /sites/Folder/SubFolder/Filename.docx"; // the file you want to get
$targetFile = $ctx->getWeb()->getFileByServerRelativePath(new SPResourcePath($server_relative_path)); // get the file
$targetFile->getUniqueId(); // do something with the file

Not sure if that helps, hope it does.

the things you can do with a File

Thanks for the reply. Unfortunately I can't make it work. Also I tried getFileByServerRelativeUrl without any luck :(

Rain-YuXia avatar May 20 '21 03:05 Rain-YuXia

@Rain-YuXia Try this

$ctx = ClientContext::connectWithClientCredentials($url, $client_id, $client_secret); // connect
$server_relative_path = " /sites/Folder/SubFolder/Filename.docx"; // the file you want to get
$targetFile = $ctx->getWeb()->getFileByServerRelativeUrl($server_relative_path); // get the file
$ctx->load($targetFile);
$ctx->executeQuery();
$targetFile->getUniqueId(); // do something with the file

You missed $ctx->load($targetFile) and $ctx->executeQuery()

febinthomas avatar Jan 18 '22 18:01 febinthomas