I got into this question while searching for a way to reuse the same image during programmatic creation of multiple nodes. It is not completely clear to me if the question is about creating nodes programmatically or from the Drupal backend, but I think it could be useful for someone if I post the solution I found to the programmatic use case too (you can skip this part and go to the manual solution if you are not interested to coding).
assuming that you already have the image file on your local file system, you have to create an image object first:
$imgUri = file_build_uri("import/default_image.jpg");
$imgFile = File::Create(['uri' => $imgUri]);
In the above code I assume that you have uploaded (e.g. via FTP) a file named "default_image.jpg" to the subdirectory "import" in your public file system, but of course you can place it wherever you want and use the name you prefer, simply change the argument to "file_build_uri" accordingly.
for each node you want to create, if you now set the $imgFile object as the value of an image field the system will reuse the same image file. Find below a sample code for creating one node with a field image:
$node = Node::create([
'type' => 'article',
'title' => 'Test article',
'field_image' => $imgFile,
Finally I would like to give a suggestion for the manual use case, that is if we need to upload the same file multiple times (e.g. in a node creation form) and do not want the system to create multiple copies of the same file on disk. In this case the solution that works for me is to:
- store the image as a separate node, e.g. by creating a content type or taxonomy just for storing "default images"
- instead of uploading the image to the target content type, we refer to the image stored at point 1 using an entity reference field. So basically we wouldn't have an image field at all in our target content type, and would replace it with an entity reference field which references one of the default images.
Needless to say the solution above is suitable for when you really have a ton of files to upload and want to avoid the disk being filled-in with duplicates of the same image. If you only have a bunch of images I think there is no better solution than the easiest one: accepting the duplications and living with them :)
Note that the latest modules for Drupal 8 which "automagically" resolve this problem are based exactly on this technique. So you can also download Media Entity for example and rely on it (along with the supporting Media Entity Browser and other useful sub-modules) to do the job for you.