自定义文件上传表单及验证

-- Submitted by Admin on Sun, 06/13/2010 - 09:54

在我们自定义表单时,文件上传验证是个比较头疼的问题,经过我多次修改推敲,终于把它写成了API,欢迎大家测试并提意见。

首先注意,表单里有文件上传,就需要定义form的一个属性如下,不然一直会提示你文件没上传:

$fields['#attributes'] = array('enctype' => 'multipart/form-data');

下面是调用部分,我以hook_user中的validate为例:

<?php
       
case 'validate':
           
//User Image
           
$file_form_name = 'user_image_file';
           
$file_size = 2000;//kb
           
$file_extra_name = array('jpg png gif');
           
$image_resolution = array('100x100');
           
$edit = file_upload_validator($file_form_name, $edit, $file_size, $file_extra_name, $image = 1, $image_resolution);
           
           
//User Nativeresume
           
$file_form_name = 'user_native_resume_file';
           
$file_size = 1000;//kb
           
$file_extra_name = array('pdf');
           
$edit = file_upload_validator($file_form_name, $edit, $file_size, $file_extra_name);
?>

核心API函数如下:

<?php
/**
* 文件上传验证函数
*/
function file_upload_validator($file_form_name, $edit, $file_size, $file_extra_name = array(), $image = 0, $image_resolution = array()) {
   
//判断文件上传表单有无值
   
if($_FILES['files']['name'][$file_form_name] != null) {
       
//文件上传大小
       
$file_limit = $file_size;
       
$extensions = $file_extra_name;
       
//文件上传验证数组
       
$validators = array(
           
'file_validate_extensions' => $extensions,
           
'file_validate_size' => array($file_limit * 1024),
        );
       
//如果是图片验证
       
if($image) {
           
$validators = array(
               
'file_validate_extensions' => $extensions,
               
'file_validate_is_image' => array(),
               
'file_validate_image_resolution' => $image_resolution,
               
'file_validate_size' => array($file_limit * 1024),
            );
        }
       
//文件保存路径
       
$destination = file_directory_path();
       
//判断文件是否上传成功,如果成功就验证
       
if($file = file_save_upload($file_form_name, $validators)) {
           
//提取$file->fid,用于存储
           
$edit[$file_form_name.'_fid'] = $file->fid;
           
//文件上传验证(自定义函数)
           
file_copy_path($file, $file_form_name, $destination);
        }
        else {
//上传失败
           
drupal_set_message("Failed to upload the file!");
        }
    }
    return
$edit;
}

/**
* 文件拷贝、路径修改函数
*/
function file_copy_path($file, $file_form_name, $destination) {
   
$fd = fopen($file->filepath, "rb");
   
//若临时文件不可读
 
if (!$fd) {
   
form_set_error($file_form_name, t('Import failed: file %filename cannot be read.', array('%filename' => $file->filename)));
  }
  else {
       
//将文件从临时目录拷贝到指定目录
        //判断有无此目录,若没有则创建该目录
       
if(!file_exists($destination)) {
            if(!
mkdir($destination, 0755)) {
               
drupal_set_message('Failed to create folder: '.$destination);   
            }
        }
       
//拷贝成功后,修改files表中该记录的文件路径字段
       
if (file_copy($file, $destination, FILE_EXISTS_REPLACE)) {
           
change_file_path($file->fid, $file->filename, $destination);
        }
        else {
           
drupal_set_message("Failed to copy file, Please make sure ".$destination." can be writed!");
        }
    }
}

/**
* 文件copy成功后,修改file的存储路径
*/
function change_file_path($fid, $filename, $destination) {
   
$sql = "UPDATE {files} SET filepath = '%s' WHERE fid = %d";
   
db_query($sql, $destination."/".$filename, $fid);
}
?>

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Allowed HTML tags: <a> <em> <strong> <code> <cite> <ul> <ol> <li> <dl> <dt> <dd> <img> <ebmed>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
16 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.