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

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'];
}
|improve this answer|||||
  • thx @Chapabu, this is great – kkatusic May 20 '13 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"),
        );
|improve this answer|||||
  • Will it work for multiple file upload? – Dushyant Joshi Sep 12 '14 at 6:43
  • Not in any easy way, it seems – Dalmaz Nov 27 '16 at 15:50

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.