I need to upload on Drupal 8 a file from an URL programmatically without using a form and a field type 'managed_file'. I'm not sure how to do this, I found different web pages on it but it's often the old version of Drupal and only some part of code.

What exactly I want to do :

  • I Have an URL (for example a PDF document, a *.doc, ...)
  • I need to save it on Drupal and create the associated record in the database

You could keep it really simple by using something like file_get_contents() to retrieve your file and save it on somewhere on the servers filesystem, presumably /sites/default/files. After that, you can put in the database whatever you want.

The thing is, drupal won't know what to do with that in most cases. Files in drupal must be associated with a file field. That's the way things work.

| improve this answer | |
  • Ok, so I use file_get_contents() and then file_save_data(). The file is correctly uploaded and I notice that a new record appears automatically in the table file_managed. So I don't need to create it ? – gduh Mar 13 '19 at 15:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.