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=‘.$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/";

}
}



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。