How to convert a file into File Entity
Question
I need to use file_copy in a custom module in D8.
The function file_copy
requires the first parameter to be a File Entity
. Here is what I have tried but it doesn't work and returns an error:
TypeError: Argument 1 passed to file_copy() must be an instance of Drupal\file\FileInterface, instance of stdClass given.
$file_path = drupal_realpath("public://Testttt58.png");
$file = (object) array(
'uid' => 1,
'uri' => $file_path,
'filemime' => mime_content_type($file_path),
'display' => 1,
'filename' => "Testttt58.png"
);
$fileUpload = file_copy($file, "public://TestFolder", FILE_EXISTS_RENAME);
Here is the output of kint($file);
How can I solve this?
Solution
Just use something like this:
use Drupal\file\Entity\File;
$file = File::create([
'uri' => $file_path,
'filemime' => mime_content_type($file_path),
'filename' => "Testttt58.png",
]);
$fileUpload = file_copy($file, "public://TestFolder", FILE_EXISTS_RENAME);
OTHER TIPS
You can use file_save_data
to save a file and create the managed file object.
e.g:
$filepath = 'public://Testttt58.png';
// Save the file, using the file contents in $data
$file = file_save_data($data, $filepath, FILE_EXISTS_REPLACE)
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange