在 Drupal5 模組中自行設計檔案上傳表單範例

edited 十一月 -1 in Drupal
這是用來上傳 mp3 或 wav 格式的音樂檔案。

function xxx_upload_form() {
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['title'] = array(
'#type' => 'textfield',
'#title' => '歌曲名稱',
'#size' => 18,
'#required' => TRUE,
'#weight' => 1
);
$form['music'] = array(
'#type' => 'file',
'#size' => 10,
'#title' => '歌曲檔案',
'#required' => FALSE,
'#weight' => 2
);
$form['creator'] = array(
'#type' => 'textfield',
'#title' => '歌手或樂團名稱',
'#size' => 18,
'#required' => FALSE,
'#weight' => 3
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
'#weight' => 4,
);
return $form;
}

function xxx_upload_form_submit($form_id, $form_values) {
global $user;
$file = file_check_upload('music');
if(!in_array($file->filemime, array('audio/mpeg', 'audio/x-wav'))) {
drupal_set_message('上傳檔案格式有誤!');
} else {
$userMusicPath = file_directory_path() . '/music';
if(!file_check_directory($userMusicPath, true) || !file_check_directory($userMusicPath .= '/' . $user->uid, true)) {
drupal_set_message('目錄無法建立,請連絡管理員!');
} else {
$userMusicPath .= '/' . uniqid() . substr($file->filename, strrpos($file->filename, '.'));
file_save_upload($file, $userMusicPath);
db_query('INSERT INTO {xxx} (uid, title, music, creator, created)
VALUES (%d, \'%s\', \'%s\', \'%s\', NOW());',
$user->uid, $form_values['title'], $file->filepath, $form_values['creator']
);
drupal_set_message('音樂上傳成功!');
}
}
return 'user/' . $user->uid;
}


模組安裝後,就可以在任意地方加入下面程式碼來進行檔案上傳:
echo drupal_get_form('xxx_upload_form');


原則上應該適用 Drupal6 ,不過我是在 Drupal5 開發的 ;)

原始討論: http://twpug.net/x/modules/newbb/viewtopic.php?topic_id=4094
Sign In or Register to comment.