How to implement ajax file upload in custom form in Drupal 8 and 9

Here we are going to create a custom form with Ajax file upload field. So final form will be as below.

Here Single and multiple files can be selected and uploaded in server using Ajax.

Assuming you have custom module with a custom form.

Read this article  for creating a custom form.

Next we are going to create a file upload field as below.

$form['upload']['image_dir'] = [
    '#type'                 => 'managed_file',
    '#upload_location'      => 'public://',
    '#multiple'             => TRUE,
    '#description'          => t('Allowed extensions: gif png jpg jpeg'),
    '#upload_validators'    => [
      'file_validate_is_image'      => array(),
      'file_validate_extensions'    => array('gif png jpg jpeg'),
      'file_validate_size'          => array(25600000)
    ],
    '#title'                => t('Upload an image file for this slide')
    ];

In order to see complete code,  download sample module here.

You can change value of  #multiple in to true and false. True means allows multiple files to upload.

You can specify upload location in #upload_location . here we have provided  ‘public://

This will be pointing to the path \sites\default\files\

You can create image directory in path  \sites\default\files\  and provide it in #upload_location as public://YOUR_DIR

After uploading file will be uploaded and marked as temporary. You can see file File tab  of content page.

While saving we have to make it permanent. So add below code in submitForm function before saving.

$file_data = $form_state->getValue(['upload' => 'image_dir']);
		 $file = \Drupal\file\Entity\File::load( $file_data[0] );
		 $file_name = $file->getFilename();
		 $file->setPermanent();
		 $file->save();

Here we will get file name which we can save it in our table.

$file_data will be an array which contains file id. If multiple files are selected , then multiple values will be there in this array.

Download complete module code here.

 

Get Free E-book
Get a free Ebook on Drupal 8 -theme tutorial
I agree to have my personal information transfered to MailChimp ( more information )
if you like this article Buy me a Coffee this will be an ispiration for me to write articles like this.

You may also like...