首页 > 代码库 > drupal form 中图片上传

drupal form 中图片上传

1.创建url 链接到form

$items[‘qianfeng/add‘] = array(
    ‘title‘ => t(‘添加信息‘),
    ‘page callback‘ => ‘drupal_get_form‘,
    ‘page arguments‘ => array(‘qianfeng_add‘,1),
    ‘file‘ => ‘videocloud_qianfeng.pages.inc‘,
    ‘access callback‘ => ‘user_is_logged_in‘,
    ‘weight‘ => -10,
    ‘type‘ => MENU_CALLBACK,
  );

创建form元素

$barcode_image 为图片路径

function qianfeng_add($form, $form_state,$barcode_id){

if(!empty($barcode_image)){
 $form[‘barcode_image_current‘] = array(
   ‘#title‘ => t(‘图片‘),
   ‘#prefix‘ => l(‘<img class="barcode_image" src=http://www.mamicode.com/‘.$barcode_image.‘>‘,$barcode_image , array("html" => true)),
   ‘#weight‘ => 3,
 );
  }
  $form[‘barcode_image‘] = array(
      ‘#type‘ => ‘file‘,
      ‘#name‘=>‘barcode_image‘,
   ‘#required‘ => false,
      ‘#weight‘ =>4
  );
  $form[‘submit‘] = array(
   ‘#title‘ => t(‘提交‘),
      ‘#type‘ => ‘submit‘,
      ‘#value‘=>‘提交‘,
      ‘#weight‘ =>5
  );
  $form[‘#attributes‘][‘enctype‘] = ‘multipart/form-data‘;
  return $form;
}

form 提交函数

function qianfeng_add_submit($form, $form_state){

       $tp = array("gif","jpg","png","bmp");
$file = $_FILES["barcode_image"];

if(!empty($file[‘name‘])){
 $path = "./sites/default/files/barcode/";
 if(!file_exists($path)){ 
    mkdir($path,0777,true);
  }
  $name = md5(time().rand(1,10000));
  $fname=$file[‘name‘];
  $ftype=explode(‘.‘,$fname);
  $picName=$path.$name.‘.‘.$ftype[1];
  if(!in_array($ftype[1], $tp)){
    drupal_set_message("图片格式不正确,正确的格式(gif,jpg,png,bmp)!",‘warning‘);
    return false;
  }
  if(intval($file[‘size‘])>2097152){
   drupal_set_message("图片大小超出2M,请上传2M以下的图片!",‘warning‘);
   return false;
  }
$id = move_uploaded_file($file[‘tmp_name‘],$picName);
$fields[‘image_name‘] = $name.‘.‘.$ftype[1];
     $fields[‘image_path‘] = "sites/default/files/barcode/";

}
}