Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By joeysantiago on
Hello,
is there a way to load a file by uri?
i can't find any function like this in the API...
thanks
[SOLUTION]
Well, i knew i could do it via select from DB... so, here's the code:
$result = db_query('SELECT f.fid
FROM {file_managed} f WHERE f.uri = :uri', array(':uri' => $uri));
[/SOLUTION]
Comments
perhaps, i should describe
perhaps, i should describe the situation a little bit more.
I'm hooking node_presave to add content coming from an external xml to nodes. One of the contents is an image. I'd like to download the image and save it to my drupal files directory if i don't have any other file with the same uri, if instead i already have a file with that uri, i'd like to rename it.
thanks!
You can do this
you can also use EntityFieldQuery
On the off chance anyone lands here looking for a way to lookup a file by name, see the first comment on https://api.drupal.org/api/drupal/includes%21file.inc/function/file_load... for an example how to do this with EntityFieldQuery.
D8 way
If you looking for D8 solution:
Thanks, this works!
Thanks, this works!
It works!
Thanks voleger!
Thanks! This was the answer
Thanks! This was the answer I personally needed. If this were stackexchange I'd upvote your comment.
Thanks
Nice idea.
Here the link https://drupal.stackexchange.com/questions/262862/load-a-file-entity-by-...
stackexchange
Okay, I upvoted it
Thanks, works for filename lookups too
Thanks voleger, this was just what I was looking for. For anyone else who wants to lookup files by filename just swap out 'uri' for 'filename'!
Load file by filename
What about if you don't know the `'public://file.xyz';`.
For example an image from https://drupal.stackexchange.com/sites/default/files/blog-images/stack.jpg and we want to get the Id. We could do it like this:
function getFileData($FileUrl) {
$FileName=drupal_basename($FileUrl);
$TargetFile = file_load_multiple(array(), array('filename' => $FileName));
$FileData= reset($TargetFile);
if($FileData):
return($FileData);
else:
return FALSE;
endif;
}
//Usage
$FileUrl="https://drupal.stackexchange.com/sites/default/files/blog-images/stack.jpg";
$FileData=getFileData($FileUrl);
//::::file id
$TheFiD=$FileData->fid;
//::::file uri
$TheUri=$FileData->uri;
//Should print 'public://blog-images/stack.jpg' or 'private://blog-images/stack.jpg'
//Upload userId
//$UploadUserId=$FileData->uid;