Friday, 12 October 2018

How to upload file using URL in drupal 8 programmatically?

Here is a simple way to upload file either file or image by URL in drupal 8. We are going to give an example for this query.
Example: First we need an url like..
        $fileurl = $fileurlval->url;             
        $name = str_replace(' ', '-', strtolower($meta_title).'.pdf');   //here meta_title is the name of your pdf or image
       
        //Get the uploaded file from the url.  
        $filedata = file_get_contents($fileurl);
       
        //Saves a file to the specified destination and creates a database entry.
        $file_directory_name = 'images'; // it means  upload folder name  
        $uploaded_file = file_save_data($filedata, "public://".$file_directory_name."/".$name, FILE_EXISTS_RENAME);
       
        // here "public://" means 'sites/default/files/' folder..
        // here $file_directory_name means we can set any folder where we want to upload..
        // here $name is name of file name..
                           
        if (!empty($uploaded_file)) { 
            $file_arr = array(
                "target_id" => $uploaded_file->id(),
                 "alt" => $uploaded_file->getFilename(),
            );       
       
            $node->field_resources_asset_tagging = $file_arr; // here field_resources_asset_tagging is file field..       
        }

So this is the way to upload file/image in drupal 8 programmatically.  


Note: If have any suggestions or issue regarding 'How to upload file using URL in drupal 8 programmatically?' then you can ask by comments.  
   

No comments:

Post a Comment

How to resolve max execution time error in drupal ?

When you found error regarding 'max_execution_time' exceed, then you can follow steps for resolve this error: Steps:   You can put t...