5

Is there any example how to set up form element with type file to upload it via AJAX. I want to be same as field image in node type article.

thx

2 Answers 2

10

Maybe this will be helpful (in a custom module):

function testmodule_forma($form, & $form_state) {
    $form['im-container'] = array(
        '#prefix' => '<div id="im-area">',
        '#suffix' => '</div>',
    );

    $form['image_file'] = array(
        '#type' => 'file',
    );

    $form['upload'] = array(
        '#type' => 'submit',
        '#value' => 'upload',
        '#submit' => array('upload_image'),
        '#ajax' => array(
            'callback' => 'upload_image',
            'wrapper' => 'im-area',
            'method' => 'replace',
            'effect' => 'fade',
        ),
    );
    return $form;
}

function upload_image($form, $form_state) {

    $file = file_save_upload('image_file', array('file_validate_extensions' => array('png gif jpg jpeg')), "public://", FILE_EXISTS_REPLACE);
    if ($file) {
        $file->status = FILE_STATUS_PERMANENT;
        file_save($file);
        $form['im-container'] = array(
            '#title' => t('Preview:'),
            '#prefix' => '<div id="im-area">',
            '#markup' => '<img src="sites/default/files/'.$file - > filename.
            '" height="250" width="250" />',
            '#suffix' => '</div>',
        );
    } else {
        drupal_set_message('No file uploaded.');
    }

    return $form['im-container'];
}
1
  • thx @Chapabu, this is great
    – kkatusic
    Commented May 20, 2013 at 13:40
4

If you are using D7, Why you are writting messy code to achieve this task?

In D7 form API we have type = managed_file which uploads file using ajax.

Try this example:

$form['image'] = array(
            '#type' => 'managed_file',
            '#title' => t('Upload Image'),
            '#default_value' => '',
            '#required' => TRUE,
            '#description' => t("Upload Image description"),
        );
2
  • Will it work for multiple file upload? Commented Sep 12, 2014 at 6:43
  • Not in any easy way, it seems
    – Dalmaz
    Commented Nov 27, 2016 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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