If folders don't exist in URI path, file_save_data() fails I am programmatically importing images and saving them via file_save_data();

$fileContentsPath = 'http://mypathtofile.com';
$uri = 'public://myfolder/mysecondfolder/filename.jpg';
$image = file_get_contents($fileContentsPath);
$file = file_save_data($image, $uri, FILE_EXISTS_REPLACE);


When I run this I get the following error: The specified file temporary://fileJ4LL4o could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.

I am pretty sure my temporary directory is configured correctly and the files folder is assigned to the apache user.

If I go into the files directory and make the directories (myfolder/mysecondfolder) via command line and rerun it works correctly. 

So the problem is that if the folders don't exist from the $uri path, it fails instead of creating the folders.
I Noticed Similar issue while saving files using 

 file_save_data();


In Drupal 8.

First I gave only first level directory to save the file as

$file = file_save_data($object-&gt;vertex_data, 'public://vertex_data.txt', FILE_EXISTS_REPLACE);


This worked fine.

But when I tried saving the file inside a subfolder as 

$file = file_save_data($object-&gt;vertex_data, 'public://objects/vertex_data.txt', FILE_EXISTS_REPLACE);


it gave me the following Error : 

File temporary://fileh1Gpl2 could not be moved/copied because the destination directory public://objects/ is not configured correctly.


The Solution for this is simple. Just use file_prepare_directory();

$directory = 'public://objects/'
file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
$file = file_save_data($object-&gt;vertex_data,  $directory . 'vertex_data.txt', FILE_EXISTS_REPLACE);


This, first creates the folder if it does not exists and then proceeds to save the respective file.