檔案上傳 預覽圖片(AJAX)

1 篇文章 / 0 new
author
檔案上傳 預覽圖片(AJAX)
function upload_ajax($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://", $replace = FILE_EXISTS_REPLACE);
    $uri = $file->uri; //uri格式 = scheme://target
    $path = variable_get('file_'.file_uri_scheme($uri).'_path') . '/' . file_uri_target($uri);
    //$wrapper = file_stream_wrapper_get_instance_by_uri($uri);
    //$path = $wrapper->getDirectoryPath() . "/" . file_uri_target($uri);
    //$c = $wrapper->dirname($uri);//get public://
    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="' . $path . '" height="250" width="250" />',
            '#suffix' => '</div>',
        );
    }
    else {
        drupal_set_message('No file uploaded.');
    }
    return $form['im-container'];
}
Free Web Hosting