ThinkPHP uploads files and how to judge whether the uploaded data is duplicated

File Upload

   1. No special processing is required to use the upload function in ThinkPHP, but it should be noted that enctype="multipart/form-data" needs to be set in the form to use the upload function.


   2. tp comes with a class for uploading files, location: Think/Upload.class.php. So the tp framework is very convenient to use. Let's take a look at the implementation code of the upload method:

    //Upload file
  public function upload(){
     if(IS_GET){
        $this->display();
        exit;
     }
       $upload = new \Think\Upload();
       $upload->maxSize=0;//File upload size
       $upload->exts = array('csv');//File suffix
       $upload->rootPath='./Public/Upload';//Upload root directory
       $upload->savePath='/';


       //Upload file
       $info=$upload->upload();
       if(!$info){
        $this->error($upload->getError());
       }else{
         $this->success('Upload successful'.$info[ 'file']['savePath'].$info['file']['savename']);
     }

  }

  3. Each uploaded file is an array that records the following information. After the file is uploaded successfully, you can use the file information to perform other data operations, such as saving to the current data table or a separate attachment data table.


For example, the following represents a field that saves upload information to a data table:

$this->success('Uploaded successfully'.$info['file']['savePath'].$info['file']['savename']);

  4. How to judge whether the information of the uploaded file is repeated, first get the data from the file, if it exists, it will be repeated without executing the added code. If it does not exist, it will be added to the database. The following is a code for judging whether the upload of the student number is repeated. After the upload is successful, this code can be executed.

 $fp=fopen($file,'r');
    if($fp){
      $fields=array('no','name','sex');
      $model=M('newstudent');
      $arrNo = $model->getField('no',true);


      $arr=array();   
      while(($row=fgetcsv($fp,1000,","))!==false){
        $row=array_combine($fields, $row);
        if(in_array($row['no'], $arrNo)){
          echo $row['no'].'存在'.'<br>';
        }else{
          $arrNo[]=$row['no'];
          $arr[]=$row;
          echo $row['no'].'导入成功'.'<br>';
        } 
        if(count($arr)==1000){
          $model->addAll($arr);
          unset($arr);
        }
      }
      if(count($arr)>0){
        $model->addAll($arr);
      }
      $this->success('Added successfully');
    }
  }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325695091&siteId=291194637