zoukankan      html  css  js  c++  java
  • drupal7 开发自定义上传、下载模块的上传功能

    关键点有两个:1.在页面上显示出上传的控件,2.代码实现文件上传到服务器的功能

    一、显示控件:

    先来看关键点1: 实现页面显示出上传控件, 关键代码:

     $form['my_file_field'] = array(
            '#type' => 'managed_file',
            '#title' => '文件', 
            )
        );   

    做过上传的功能的人,会发现上面的代码值能实现在页面显示上传控件,但是没有限制上传大小。另外需要注意的是,上传的路径和格式也必须在定义该控件的时候指定。完整的上传控件的代码实现:

    define("UPLOAD_Base_Path", "public://myfilezjf");
    $str_upload_extend='doc docx xls xlsx ppt pptx ';//这里写允许的上传格式
        $SIZE_M=8;//限制大小,单位M
        $form['my_file_field'] = array(
            '#type' => 'managed_file',
            '#title' => '文件',
            '#description' => '格式限制:'.$str_upload_extend.' 大小限制:'.$SIZE_M.'M以内',
            '#upload_location' => UPLOAD_Base_Path,
            '#upload_validators' => array(
                'file_validate_extensions' => array($str_upload_extend),//限制上传文件后缀
                // Pass the maximum file size in bytes
                'file_validate_size' => array($SIZE_M*1024*1024),//限制大小
            )
        );   

    二、上传代码具体实现关键点:2:实现上传的具体代码:

    1 function uploadview_form_submit($form, &$form_state){   
    2 //     Load the file via file.fid.  
    3     $file = file_load($form_state['values']['my_file_field']);
    4     $file->status = FILE_STATUS_PERMANENT;
    5     file_save($file);
    6 
    7     drupal_set_message('保存成功'); 
    9 }

    需要特别说明一下的是,第4行代码,就是为文件制定了satus=1,即永久保存的文件,不会被drupal自动删除;否则是status=0,指的是临时文件,会被drupal定期自动删除

    三、完全意义上的实现

    到前面两步,我们已经实现了上传的功能,但是怎么查看上传的文件列表,从而进行下载和管理呢?就是你怎么从数据库中查出你做额这个页面的上传的文件呢?

    这里我们需要了解,凡是上传的文件都会在file_manage表中保存一条记录,上面说到的status就是该表的属性之一,下面就是一条该表的记录:

    但是其他模块上传的文件也会在这张表中留下痕迹,怎么区分呢?目前我能给出的方案就是,单独再建立一张表,两张表进行关联,表结构为:fid int(10) PK, title varchar(255)

    完整代码如下:

    3.1 upload.module文件:

    <?php 
    
    function upload_menu()
    {
        $items=array();
        
        //管理列表
        $items['admin/upload']=array(
            'title' => '上传', 
            'description' => '上传',
            'page callback' => 'manage_upload_list', 
            'access arguments' => array('access content' ), 
            'type' => MENU_NORMAL_ITEM,
            'file' => 'upload.admin.inc',
        );
           
        //进行上传
        $items['upload']=array(
            'title' => '上传--测试',
            'description' => '上传',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('uploadview_form'),
            'access arguments' => array('to upload' ),
            'type' => MENU_NORMAL_ITEM,
            'file' => 'upload.pages.inc',
        
        );
        
        //下载列表
        $items['upload/list']=array(
            'title'=>'下载列表',
            'description' => '下载列表',
            'page callback' => 'download_list', 
            'access arguments' => array('to upload' ),
            'type' => MENU_NORMAL_ITEM,
            'file' => 'upload.pages.inc',
        );
        
        //删除
        $items['admin/upload/%/delete']=array(
            'title'=>'删除',
            'description'=>'删除',
            'page callback'=>'drupal_get_form', 
            'page arguments'=>array('upload_delete_confirm',2),
            'access arguments' => array('manage upload' ),
            'type' => MENU_NORMAL_ITEM,
            'file' => 'upload.admin.inc',
            
        );
        
        return $items;
    }
    
    function upload_permission(){
        return array(
            'manage upload'=>array(
                'title'=>t('管理下载权限')
            ),
            'to upload'=>array(
                'title'=>t('进行上传')
            ),
            
        );
    }
     
    function upload_block_info()
    {
        $blocks['upload_download']=array(
            'info'=>t('下载区域'),
            'weight'=>1,
            'status'=>1,
            'region'=>'Sidebar first'
        );
     return $blocks;   
    }
    
    function upload_block_view($delta='')
    {
        $block=array();
        
        switch ($delta)
        {
            case 'upload_download':
                $block['subject']='下载';
                $block['content']=get_mydownload_block();
                break;
        }
     return $block;
    }
    
    
    function get_mydownload_block()
    {
        
        $str_query="SELECT c_f_u.fid AS fid, c_f_u.title AS title, f_m.uri AS uri, f_m.filename AS filename
                    FROM 
                    custom_file_upload c_f_u
                    INNER JOIN file_managed f_m ON c_f_u.fid=f_m.fid
                    ORDER BY f_m.timestamp DESC
                    LIMIT 10 OFFSET 0 ";
                   
        $content = db_query($str_query);
    
        $lists=array();
    
    
        $output='<div class="item-list">';
        $_count=1;
        if ($content) {
            $output.='<ul>';
            $length=count($content);
            foreach ($content as $data)
            {
                $class='';
                if($_count==1) {//第一个
                    $class='class="first"';
                }
                elseif ($_count==$length)//最后一个
                {
                    $class='class="last"';
                }
    
                $url_head='http://'.$_SERVER['HTTP_HOST'].'/drupal755/sites/default/files/';
                $url=$url_head.ltrim($data->uri,'public://');
                $html_h=l($data->title,$url); 
                $output.='<li '.$class.'>'.$html_h.'</li>';
                $_count++;
            }
            $output.='</ul>';
        }
        else 
        {
            $output.='<p>No Content</p>';
        }
        $output.='</div>';
    
        if ($_count>=5) {
            $url='http://'.$_SERVER['HTTP_HOST'].'/drupal755/upload/list';
            $output.='<div style="text-align:right;100%">'.l('更多>>',$url).'</div>';
        }
         
        return  $output;
    }
    
    function upload_theme(){
        return array(
            'hoyand_paiko_thumb_upload' => array(
                'render element' => 'element',
            ),
        );
    }
    
     
    View Code

        3.2 upload.pages.inc文件

    <?php
    
    define("UPLOAD_Base_Path", "public://myfilezjf");
    
    function  uploadview_form($form, &$form_state){
        //gif png jpg jpeg txt 
        $str_upload_extend='doc docx xls xlsx ppt pptx ';//这里写允许的上传格式
        $SIZE_M=8;//限制大小,单位M
        $form['my_file_field'] = array(
            '#type' => 'managed_file',
            '#title' => '文件',
            '#description' => '格式限制:'.$str_upload_extend.' 大小限制:'.$SIZE_M.'M以内',
            '#upload_location' => UPLOAD_Base_Path,
    //         '#default_value' => empty($user->picture->fid) ? 0 : $user->picture->fid,
    //         '#theme' => 'hoyand_paiko_thumb_upload',  //留意这个我们为他增加了一个theme
            '#upload_validators' => array(
                'file_validate_extensions' => array($str_upload_extend),//限制上传文件后缀
                // Pass the maximum file size in bytes
                'file_validate_size' => array($SIZE_M*1024*1024),//限制大小
            )
        );   
        
        $form['title']=array(
            '#type'=>'textfield',
            '#title'=>t('名称'), 
            '#size' => 30,
            '#required' => TRUE,
        );
            
    //     Add the buttons.
        $form['buttons'] = array();
        $form['buttons']['#weight'] = 100;
        $form['buttons']['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Save'),
            '#weight' => 5,
            '#submit' => array('uploadview_form_submit'),
            '#prefix' => '<div >',
            '#suffix' => '</div>',
        );
        
        $form['#validate'][] = 'pk_settings_form_validate';
        
        return $form;
    }
     
    
    function uploadview_form_submit($form, &$form_state){   
    //     Load the file via file.fid.  
        $file = file_load($form_state['values']['my_file_field']);
        $file->status = FILE_STATUS_PERMANENT;
        file_save($file);
    
        insert_customfile($file->fid,$form_state['values']['title']);//插入custom_file_upload表
        drupal_set_message('保存成功'); 
    }
    
    function insert_customfile($fid,$title="")
    {
    
        db_insert('custom_file_upload')
        ->fields(
            array(
                'fid'=>$fid,
                'title'=>$title
            )
            )->execute();
    }
     
    function pk_settings_form_validate($form, &$form_state) {
        
    }
    
    
    function download_list()
    {
        
        $query = db_select('custom_file_upload','c_f_u');
         $query->join('file_managed','f_m','c_f_u.fid=f_m.fid');
            
         $objects=$query->extend('PagerDefault')
         ->fields('c_f_u', array( 'fid','title')) 
         ->fields('f_m', array( 'uri','filename','timestamp')) 
    //      ->condition('f_m.status',1) 
         ->orderBy('f_m.timestamp','DESC')
         ->limit(10)
         -> execute() ; 
    
        $output=""; 
        $rows = array();
        $title_length=25;
        if (true) { 
           
            foreach ($objects as $key => $object) {
    //             debug($object);
                $row = array(); 
                $title="";
                if (strlen($object -> filename)>$title_length) {
                     $title= drupal_substr($object -> filename,0,50).'...' ; 
                }
                else {
                    $title= $object -> filename ; 
                }
                $url_head='http://'.$_SERVER['HTTP_HOST'].'/drupal755/sites/default/files/';
                $url=$url_head.ltrim($object->uri,'public://'); 
                $row['title']=l($object->title,$url);
                $row['created']=date('Y-m-d h:m:s',$object->timestamp);
               
                $rows[] = $row; 
            }
            $results=$rows;
            $output .= theme('table', array('rows' => $rows));
            $output .= theme('pager');
        }
        else 
        {
           $output="暂无数据"; 
        }
        
       return  $output;
    }
    View Code

    3.3 upload.admin.inc 文件

    <?php 
    /*管理列表*/
    function manage_upload_list()
    {
        $output = "";
        $query = db_select('custom_file_upload','c_f_u');
                 $query->join('file_managed','f_m','c_f_u.fid=f_m.fid');
       
        $objects = $query ->extend('PagerDefault')
                    ->fields('f_m',array('fid','uri','filename'))
                    ->fields('c_f_u',array('title'))
                    ->orderBy('f_m.fid','DESC')
                    ->limit(2)
                    -> execute();
        
        $rows = array();
        $title_length=25;
        foreach ($objects as $key => $object) {
            $row = array();
            $title="";
            if (strlen($object -> filename)>$title_length) {
                $title= drupal_substr($object -> filename,0,50).'...' ; 
            }
            else {
                $title= $object -> filename ; 
            }
            $url_head='http://'.$_SERVER['HTTP_HOST'].'/drupal755/sites/default/files/';
            $url=$url_head.ltrim($object->uri,'public://'); 
            $row['title']=l($object->title,$url);
            $row[]    = array('data' => l(t('删除'), 'admin/upload/'.$object->fid.'/delete')); 
            $rows[] = $row;
        }
        $output .= theme('table', array('rows' => $rows));
        $output .= theme('pager');
        
        return $output;
        
    }
    
    /**留言--删除页面
     * Form constructor for the node deletion confirmation form.
     *
     * @see node_delete_confirm_submit()
     */
    function upload_delete_confirm($form, &$form_state, $fid) {
        $form['fid'] = array(
            '#type' => 'hidden',
            '#default_value'=>$fid
        );
        
         $object=db_query('select title from {custom_file_upload} where fid= :fid ',array(':fid'=>$fid))
        ->fetch(); 
        // Always provide entity id in the same form key as in the entity edit form.
        return confirm_form($form,
            t('Are you sure you want to delete %title?', array('%title' => $object->title)),
            '/zjf',
            t('This action cannot be undone.'),
            t('Delete'),
            t('Cancel')
            );
    }
    
    /**
     * Executes node deletion.
     *
     * @see node_delete_confirm()
     */
    function upload_delete_confirm_submit($form, &$form_state) {
        if ($form_state['values']['confirm']) {
            $fid=$form_state['values']['fid'];
            $file = file_load($fid);
            file_delete($file, TRUE); 
           
            $num_deleted = db_delete('custom_file_upload')
            ->condition('fid', $fid)
            ->execute();
    
            cache_clear_all();
            //watchdog('content', '@type: deleted %title.', array('@type' => $node->type, '%title' => $node->title));
            drupal_set_message(t('删除成功'));
        }
    
        $form_state['redirect'] ='admin/upload' ;//  '<front>'
    }
    View Code

     

     

     

  • 相关阅读:
    常用linux命令及其设置
    shell脚本编写步骤及其常用命令和符号
    浏览器访问php脚本通过sendmail用mail函数发送邮件
    windows server 定期备份数据库脚本
    图片垂直水平居中
    "!function",自执行函数表达式
    jQuery(function(){})与(function(){})(jQuery) 的区别
    在Windows Server 2019通过Docker Compose部署Asp.Net Core
    Redis集群同步问题
    webapi跨域使用session
  • 原文地址:https://www.cnblogs.com/zjfblog/p/6206643.html
Copyright © 2011-2022 走看看