How to attach an image or file to node in Drupal 8 programmatically

Posted by admin on Tue, 01/30/2018 - 09:09

Quick code sample on how to get and attach an image or file to node or other entity programmatically in Drupal 8.

Here's an example how you could save an image to node if you get this with file_get_contents

use \Drupal\node\Entity\Node;
 
// Create file object from remote URL.
$data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png');
$file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_REPLACE);
 
// Create node object with attached file.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',
  'field_image' => [
    'target_id' => $file->id(),
  ],
]);
$node->save();

If you have an image already exists in you file system - so you could just attach it without any additional file manipulation.

use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;
 
// Create file object from a locally copied file.
$uri  = file_unmanaged_copy('public://source.jpg', 'public://destination.jpg', FILE_EXISTS_REPLACE);
$file = File::Create([
  'uri' => $uri,
]);
$file->save();
 
// Load existing node and attach file.
$node = Node::load(1);
$node->field_image->setValue([
  'target_id' => $file->id(),
]);
$node->save();

And special thanks to Drupal 8 developers - you could easily create an image placeholder!
Just like this:

use \Drupal\node\Entity\Node;
 
$node = Node::create([
  'type'  => 'article',
  'title' => 'Generated image test',
]);
$node->field_image->generateSampleItems();
$node->save();
×

Hey! Don't miss a new cool stuff!

Comments

Rent a car Beog... (not verified)

Great post. Keep up with good work. Please book your vehicle here: Rent a car Beograd

Rent a car Beog... (not verified)

Great post. Keep up with good work. Please book your vehicle here: Rent a car Beograd

saJONATHANTURLEY (not verified)

Lets have a look at a recent news item that is quite
entertainmentbee.com
themoviesbio.com
petrefine.com

It will be more fun, and you won't have to worry about
thepetsabout.com
happylifestyletrends.com
restaurantsnearme-opennow

bet600dot (not verified)

Everything is going to be alright. Are we really being honest
frasesparaenamorarz.com
fras-es.com
punaisesdelit.org
groupe-sanguine.fr
meilleur-gps.fr

Roman khan (not verified)

I discovered your blog web site on the internet and appearance many of your early posts. Always maintain in the really good operate. I simply additional the Feed to my MSN News Reader. Looking for toward reading a lot more of your stuff at a later time!… facebook login

ZeronDib (not verified)

cialis from canada no prescription avatars
cialis 5mg canada announcements
cialis over counter
- canada cialis
[url=http://cialiswalmartpharm.com]cialis over counter at walmart
[/url] cialis 5mg canada username

럭키걸 Lucky girl (not verified)

https://www.ekffo150.com/theking
https://www.ekffo150.com/merit
https://www.ekffo150.com/yes
https://www.ekffo150.com/first
https://www.ekffo150.com/sands
https://www.ekffo150.com/joy
https://www.ekffo150.com/royal
https://www.ekffo150.com/starclub
https://www.ekffo150.com/asian
https://www.ekffo150.com/superman
https://www.ekffo150.com/gatsby
https://www.ekffo150.com/33
https://www.ekffo150.com/oncasino
https://www.ekffo150.com

https://www.ajp4949.com/theking
https://www.ajp4949.com/merit
https://www.ajp4949.com/sands
https://www.ajp4949.com/first
https://www.ajp4949.com/33casino
https://www.ajp4949.com/worldcasino
https://www.ajp4949.com/korea
https://www.ajp4949.com/

https://www.bgj4949.com/
https://www.bgj4949.com/sands
https://www.bgj4949.com/theking
https://www.bgj4949.com/first
https://www.bgj4949.com/yes
https://www.bgj4949.com/33
https://www.bgj4949.com/world
https://www.bgj4949.com/super
https://www.bgj4949.com/korea
https://www.bgj4949.com/gatsby

https://www.dnfl4949.com/
https://www.dnfl4949.com/first
https://www.dnfl4949.com/merit
https://www.dnfl4949.com/theking
https://www.dnfl4949.com/sands
https://www.dnfl4949.com/yescasino
https://www.dnfl4949.com/gatsby
https://www.dnfl4949.com/corea
https://www.dnfl4949.com/33casino
https://www.dnfl4949.com/f1casino

https://www.skfl4949.com/
https://www.skfl4949.com/firstcasino
https://www.skfl4949.com/meritcasino
https://www.skfl4949.com/sandscasino
https://www.skfl4949.com/thekingcasino
https://www.skfl4949.com/yescasino
https://www.skfl4949.com/gatsbycasino

uzair (not verified)

When do you think this Real Estate market will go back right side up? Or is it still too early to tell? We are seeing a lot of housing foreclosures in Winter Park Florida. What about you? I would love to get your feedback on this. Advanced Medicine

seo (not verified)

Rattling clean internet site , thanks for this post. vận chuyển việt đài

chrisevan55 (not verified)

I’m very happy to read this. This is the type of manual that needs to be given and not the accidental misinformation that’s at the other blogs. Appreciate your sharing this greatest doc. 현서 페이지

website Ranker (not verified)

Thank you so much for the post you do. I like your post and all you share with us is up to date and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job. aumentar la capacidad pulmonar

amapsAsd (not verified)

how much is cialis in canada [url=https://cialisjla.com/ ]buy generic cialis[/url] cialis online canada paypal

seo (not verified)

Chaga mushroom coffee been recently brought to plenty of everything about simply because of the Ukrainian article author Alexandr Solzhenitsyn by it’s new ‘Cancer Ward’ in which traditional qualities is generally cured of a tumors on the help consume. Siberian Chaga click here

weackHtf (not verified)

discount cialis [url=https://cialishav.com/ ]cialis cost at walmart[/url] cialis on the web

Abbasiseo Abbasiseo (not verified)

I’m really loving the theme/design of your website. Do you ever run into any internet browser compatibility issues? A couple of my blog audience have complained about my site not working correctly in Explorer but looks great in Chrome. Do you have any advice to help fix this problem? read more

uzair (not verified)

I dont agree with all of the points made but still a good read cheers. 1440 kmed

weackAni (not verified)

Verapamil [url=https://pharmacyken.com/ ]my canadian pharmacy rx reviews[/url] how much do prescription drugs cost without insurance?

Mueed Ahmed (not verified)

The way you write, you are really a professional blogger.:~,-’ Listing

modoSwa (not verified)

generic cialisis [url=https://ckacialis.com/ ]ordering cialis in canada[/url] comprar cialis online

muhammad AK (not verified)

Wir haben es schon oft gesagt - wenn Sie ein faires Spiel spielen möchten, das Ihnen gute Gewinnchancen bietet, sollten Sie nur in seriösen, vollständig regulierten Casinos spielen. Ich habe diese großartigen betway Online-Casinos gefunden, die großartige Spielerlebnisse und Boni für Sie bieten! Schau sie dir an.

uzair (not verified)

When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three emails with the same comment. Is there any way you can remove me from that service? Cheers! 대밤 도메인

uzair (not verified)

I also recommend HubPages itself, and Squidoo, which is similar. 대밤 주소

Juztincig (not verified)

informative durvet ivermectin paste for humans
feona ivermectin covid-19
ivermectin 3mg
- is stromectol fda approved for lice
[url=http://ivermectinforhuman.com/#]ivermectin for scabies
[/url] miao ivermectin for puppies

ZevinVep (not verified)

cialis find all posts by
cialis generic online picture/text
cialis in walmart
- cialis 20 mg 4 tablet you cannot edit your posts in this forum
[url=http://cialiswa1mart.com]cialis over the counter
[/url] low cost cialis

seo person (not verified)

The subsequent time I learn a weblog, I hope that it doesnt disappoint me as a lot as this one. I mean, I know it was my option to read, however I really thought youd have something attention-grabbing to say. All I hear is a bunch of whining about one thing that you would fix for those who werent too busy in search of attention. seo

uzair (not verified)

I’m not that much of a online reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back in the future. Cheers forex trading online course

Anonymous (not verified)

If cannabis can be made into Ethanol then we need to modify it to make it work better and use those genetic differences which allow for low water in production to insure that we do not get price spikes in times of drought in the ethanol we use for fuel. Additionally if the plant can be used to "get high" then we need to modify it so that will not occur or that the leaching into the soil or waterways does not contain high levels of THC as it would be problematic. Medical Marijuana Strains for sale

Roman khan (not verified)

Dreamin. I love blogging. You all express your feelings the right way, because they are your feeling, focus on your blog it is great. hotmail entrar direto

uzair (not verified)

When visiting blogs” i always look for a very nice content like yours .     more information

seo person (not verified)

I discovered your blog site internet site on the search engines and appearance some of your early posts. Always maintain within the excellent operate. I recently additional increase your Feed to my MSN News Reader. Seeking forward to reading much more on your part down the road!… hotmail sign in

smithseo (not verified)

if you really need to become expert in driving, your really need to enroll in a driving school,. 강남 오피

Zeterdup (not verified)

sulaj does stromectol work for scabies
nonsexual stromectol merck
where to buy ivermectin
- buy stromectol 24 mg pills
[url=http://stromectol-ivermectin.com/#]stromectol 3 mg for scabies
[/url] nakonec stromectol lyme

ghazii (not verified)

This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. agen judi poker

แฮนดิแคป (not verified)

แฮนดิแคป
The best football betting website, football betting website, the best online casinos supervised by experts and professional teamแฮนดิแคป

แทงบอล (not verified)

แทงบอล
We have quality staff to take care of you 24 hours a day, safe, comfortable, no worries.

alex (not verified)

แฮนดิแคป Betting is the most return rate in betting. You can bet in any team that you want to bet. Also, it real live time betting so you cannot miss this bet at all, I gaurantee you.

naza55 naza (not verified)

NAZA.It has all the online bets you want to play. There are many promotions with benefits to participate. Play through any smartphone, complete, convenient, our website.

123maxx (not verified)

quite certain I’ll learn many new stuffดูราคาบอล

123maxx (not verified)

แฮนดิแคป Online casinos It consists of Baccarat games, slots, card games, roulette and many other games.

uzair (not verified)

I tend to think the same thing about the subject but now I saw your recent blog entry on it and it changed my mind completely. check this link

momo (not verified)

Flaming Foxslot is just like you at the casino but In online. There everything like real casino

seo (not verified)

Chaga mushroom coffee been recently brought to plenty of everything about simply because of the Ukrainian article author Alexandr Solzhenitsyn by it’s new ‘Cancer Ward’ in which traditional qualities is generally cured of a tumors on the help consume. Siberian Chaga buy documents

คาสิโน (not verified)

คาสิโนออนไลน์Bet instantly, anytime, anywhere! Available on all platforms Both computer and mobile You can bet as soon as you want, no matter where you are.

uzair (not verified)

It’s actually a nice and useful piece of info. I’m happy that you shared this helpful information with us. Please stay us up to date like this. Thanks for sharing. pug puppies for sale

anus (not verified)

Good – I should certainly pronounce, impressed with your web site. I had no trouble navigating through all tabs as well as related info ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or something, site theme . a tones way for your customer to communicate. Nice task. Natural Ingredients

mueed Ahmed (not verified)

very good submit, i actually love this website, keep on it best wireless earphones

justin (not verified)

Music started playing anytime I opened this web site, so annoying! apartment for sale in istanbul

Zormandow (not verified)

buy cialis using switch
cialis erection
cialis 5mg price cvs
- discount generic cialis
[url=http://vtadalafil.com/#]teva tadalafil
[/url] legal cialis

Zormandow (not verified)

buy cialis using switch
cialis erection
cialis 5mg price cvs
- discount generic cialis
[url=http://vtadalafil.com/#]teva tadalafil
[/url] legal cialis

Add new comment