How to upload file in drupal using custom code ?

    You have to create a custom module for it. Create a upload form first:
    <?php
     
    function modulename_upload_form(){
       
    $form['#attributes'] = array('enctype' => 'multipart/form-data');
       
    $form['data_file'] = array(
           
    '#type' => 'file',
           
    '#title' => t('Select File')
        );
       
    $form['submit'] = array(
           
    '#type' => 'submit',
           
    '#value' => t('Upload');
        );
        return
    $form;
      }
    ?>
    Then Create Form Submit Function which can do the actual process
    <?php
    function modulename_upload_form_submit($form, &$form_state) {
    //You can define these limitations as per your requirements 
     
    $limitations = array ('file_size' => 1000000, 'extensions' => 'jpg gif pdf', 'resolution' => '', 'user_size' => '') ;

     
    $validations = array(
       
    'file_validate_extensions' => array($limitations['extensions']),
       
    'file_validate_image_resolution' => array($limitations['resolution']),
       
    'file_validate_size' => array(
           
    $limitations['file_size'],
           
    $limitations['user_size']
        ),
      );

     
    // Now this fuinctions save the file to files directory If some other path you can mention instead
     
    if ($file = file_save_upload('data_file', $validations, file_directory_path())) {
       
    // Here we can get $file object which can be used to save path into database or do some other processing
     
    }
    }
    ?>
    0