function image_example_style_form($form, &$form_state) {
$form['image_example_image_fid'] = array(
'#title' => t('Image'),
'#type' => 'managed_file',
'#upload_validators' => array('file_validate_extensions' => array('jpg png bmp jpeg')), //允许上传文件的类型
'#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
'#default_value' => variable_get('image_example_image_fid', ''),
'#upload_location' => 'public://image_example_images/',//指定上传的位置
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
return $form;
}
function image_example_style_form_validate($form, &$form_state) {
if (!isset($form_state['values']['image_example_image_fid']) || !is_numeric($form_state['values']['image_example_image_fid'])) {
form_set_error('image_example_image_fid', t('Please select an image to upload.'));
}
}
function image_example_style_form_submit($form, &$form_state) {
if ($form_state['values']['image_example_image_fid'] != 0) {
$file = file_load($form_state['values']['image_example_image_fid']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file); //保存图片信息到数据库中 表file_managed中
file_usage_add($file, 'image_example', 'sample_image', 1);//在表file_usage中记录一个文件的添加,删除该文件时会根据该记录去查询删除
variable_set('image_example_image_fid', $file->fid);
drupal_set_message(t('The image @image_name was uploaded and saved with an ID of @fid and will be displayed using the style @style.', array('@image_name' => $file->filename, '@fid' => $file->fid, '@style' => $form_state['values']['image_example_style_name'])));
}
// If the file was removed we need to remove the module's reference to the
// removed file's fid, and remove the file.
elseif ($form_state['values']['image_example_image_fid'] == 0) {
// Retrieve the old file's id.
$fid = variable_get('image_example_image_fid', FALSE);
$file = $fid ? file_load($fid) : FALSE;
if ($file) {
// When a module is managing a file, it must manage the usage count.
// Here we decrement the usage count with file_usage_delete().
file_usage_delete($file, 'image_example', 'sample_image', 1);//删除表file_usage中的记录,
file_delete($file); //删除文件和数据库中(表file_managed和表file_usage)的记录
}
variable_set('image_example_image_fid', FALSE);
drupal_set_message(t('The image @image_name was removed.', array('@image_name' => $file->filename)));
}
// Save the name of the image style choosen by the user.
variable_set('image_example_style_name', $form_state['values']['image_example_style_name']);
}