Home > PHP Framework > ThinkPHP > Detailed explanation of how ThinkPHP implements image uploading

Detailed explanation of how ThinkPHP implements image uploading

藏色散人
Release: 2021-08-18 09:02:10
forward
2847 people have browsed it

The following tutorial column of thinkphp framework will introduce to you how ThinkPHP implements the image upload function. I hope it will be helpful to friends in need!

Let’s go directly to the example, which includes single image file upload, multiple image file upload, and some operations of deleting files. When deleting the database, only the file path in the database is deleted, not Delete the files in the server together and cause the server to explode...

The custom method in function.php in the common folder in TP:

<?php
//文件上传类(可以设置多个参数)
function upload($file=null,$maxSize=0,$exts=0,$savePath=&#39;&#39;)
{
  //调用
  $upload = new \Think\Upload();// 实例化上传类
  $upload->maxSize  = $maxSize;// 设置附件上传大小
  $upload->exts   = $exts; //array(&#39;jpg&#39;, &#39;gif&#39;, &#39;png&#39;, &#39;jpeg&#39;); 设置附件上传类型
  $upload->savePath = $savePath; // 设置附件上传目录
  // 上传文件
  //如果单个文件还是多个文件
  if($file){
   $info = $upload->uploadOne($file);
  }else{
  $info = $upload->upload();
  }
  //判定是否文件上传成功de
  if(!$info) {
    return false;
  }else{
  // 上传成功,
    return $info;
  }
}
//上传图片
function fab_upload($files ,$maxSize = 0,$exts = null,$savePath = &#39;&#39;)
{
  //判定文件信息是否为空
  if(empty($files)){
    return false;
  }
  if($exts === null){
    $exts = array(&#39;jpg&#39;, &#39;gif&#39;, &#39;png&#39;, &#39;jpeg&#39;);
  }else{
    $exts = 0;
  }
  $tmp = array();
  //将文件信息(数组)用foreach循环遍历,
  foreach($files as $k => $v){
  //判定文件大于0之后,将遍历value作为参数传入upload方法
    if($v[&#39;size&#39;] > 0){
      $res = upload($v,$maxSize,$exts,$savePath);
      //如果传入成功就会将文件存储路径传入数组$tmp[]之中
      if($res){
        $tmp[$k] = $res[&#39;savepath&#39;].$res[&#39;savename&#39;];
      }
    }
  }
  //将存储传入文件路径的数组return回去
  return $tmp;
}
?>
Copy after login

In fact, no matter which file is uploaded, it is It needs to be controlled by the $_FILES variable area.

The above method is fab_upload calling the upload method;

In HTML, our form is written by Jiang Zi:

<form action="{:U(&#39;Index/infoupload&#39;)}" method="post"style="overflow: hidden;clear: both;" enctype="multipart/form-data">
<p class="contact_r col-md-4">
  <label class="contact_rc contact_file"><span><b>入台證:</b><input class="inp_zj1" type="file" name="rutaiimg" ></span></label>
  <!-- <a class="contact_sp fancybox" href="images/txz1.jpg" rel="external nofollow" rel="external nofollow" >如圖示</a> -->
</p>
<p class="contact_r col-md-4">
  <label class="contact_rc contact_file"><span><b>通行證:</b><input class="inp_zj2" type="file" name="tongxingimg" ></span></label>
  <!-- <a class="contact_sp fancybox" href="images/txz1.jpg" rel="external nofollow" rel="external nofollow" >如圖示</a> -->
</p>
</form>
Copy after login

Controller How to handle uploaded files (splicing path and file name, and files that need to be deleted if the storage fails, similar to a callback)

/*调用写好的方法进行验证*/
$new_thumb = fab_upload($_FILES);
// var_dump($new_thumb);die;
$input[&#39;data&#39;][&#39;addtime&#39;]=time();//生成申请时间
$input[&#39;data&#39;][&#39;pretime&#39;]=strtotime($input[&#39;data&#39;][&#39;pretime&#39;]);//将传过来的日期转换成时间戳
if($new_thumb && count($new_thumb) > 0){
    $input[&#39;data&#39;] = array_merge($input[&#39;data&#39;],$new_thumb);
}
$f = $customer->add($input[&#39;data&#39;]);
if($f){
    $this->display(&#39;Index/infosuccess&#39;);
    // $this->success("添加成功!",U(&#39;Index/infocheck&#39;,array(&#39;iccid&#39;=>$input[&#39;data&#39;][&#39;iccid&#39;])));
}else{//数据添加失败即删除照片
    if($new_thumb){
      $p = C(&#39;UNLINK_PATH&#39;).$new_thumb;
      unlink($p);
    }
    $this->error("添加失败!证件可能已存在");
}
Copy after login

The UNLINK_PATH variable is defined in the config file in ThinkPHP and is based on the path.

<?php
return array(
  &#39;DB_TYPE&#39;  => &#39;mysql&#39;, // 数据库类型
  &#39;DB_HOST&#39;  => &#39;localhost&#39;, // 服务器地址
  &#39;DB_NAME&#39;  => &#39;urban&#39;, // 数据库名
  &#39;DB_USER&#39;  => &#39;root&#39;, // 用户名
  &#39;DB_PWD&#39;  => &#39;123456&#39;, // 密码
  &#39;DB_PORT&#39;  => 3306, // 端口
  &#39;DB_PREFIX&#39; => &#39;fab_&#39;, // 数据库表前缀
  &#39;DB_CHARSET&#39;=> &#39;utf8&#39;, // 字符集
  &#39;CHECK_ROOT&#39; => true, //开启rbac权限
  &#39;TMPL_CACHE_ON&#39; => false,    // 是否开启模板编译缓存,设为false则每次都会重新编译
  &#39;ACTION_CACHE_ON&#39; => false, // 默认关闭Action 缓存
  &#39;HTML_CACHE_ON&#39;  => false,  // 默认关闭静态缓存
  &#39;FILE_PATH&#39;=>&#39;http://localhost/urban/Uploads/&#39;,
  &#39;WEB_PATH&#39;  =>  &#39;http://localhost/urban/index.php/&#39;,
  &#39;WEB_URL&#39;  =>  &#39;http://localhost/urban/&#39;,
  &#39;UNLINK_PATH&#39;  =>  &#39;./Uploads/&#39;,
  &#39;PWD_KEY&#39;  => &#39;jeiskAsdlLsdfqaiocvwphxzbtu&#39;,
  &#39;AUTO_LOGIN_TIME&#39;=>3600 * 24 * 7,
  &#39;SHOW_PAGE_TRACE&#39;=>true, //追踪模式
  &#39;MY_CATCH_DIR&#39; =>&#39;./cache/&#39;, //缓存目录
  &#39;CODE_PATH&#39; =>&#39;http://localhost/urban/fabp/phpqrcode/&#39;,  // 存放二维码的目录
  &#39;qq_face&#39; =>&#39;http://localhost/urban/Public/site/images/arclist/&#39;,   //qq表情路径
  &#39;wxlogin&#39; => array(
    &#39;appid&#39; => &#39;wx35f5b9e9b90539ae&#39;,
    &#39;AppSecret&#39; => &#39;4de424bee1529a8abeda9c0c52aad3aa&#39;,
    &#39;callback&#39; => &#39;http://localhost/urban/index.php/Home/Login/call_back.html&#39;
    ),
  &#39;topic_pass&#39;=>false,  //是否开启话题审核
);
Copy after login

After adding, it is natural to add and delete the function on the background management module

When displaying the picture above, use the absolute path of the HTTP protocol to splice it out and display the picture;

The deletion of pictures is based on the entry file index.php, which is the upload folder under the current folder;

Remember that calling the upload and uploadone methods in ThinkPHP only returns the uploaded file. In the storage location under the upload folder, "'2016-09-02/57c94e71f0916.png'" (this is also the storage location)

So whether it is deleted or displayed, it needs to be spliced ​​using the C method

if(IS_POST){
    $input=I(&#39;post.&#39;);
    $ids=implode(&#39;,&#39;,$input[&#39;id&#39;]);
    $brand=D(&#39;brand&#39;);
    $img=$brand->where("brand_id in ($ids)")->getField(&#39;thumb&#39;,true);
    foreach($img as $v){
      $p = C(&#39;UNLINK_PATH&#39;).$v;
      unlink($p);
    }
    $res=$brand->where("brand_id in ($ids)")->delete();
    if($res){
      $this->success("删除运营商品牌成功!");
    }else{
      $this->error("删除运营商品牌失败!");
    }
}
Copy after login

The reason why foreach is used; is because the ID passed is not the only one; it is multiple selection and deletion;

How to select multiple selections and pass the value of the corresponding column ID

<foreach name="list" item="v">
  <tr>
    <td class="center" width="80px">
      <label>
        <input type="checkbox" class="ace" name="id[]" value="{$v.brand_id}"/>
        <span class="lbl"></span>
      </label>
    </td>
    <td>{$v.brand_name}</td>
  </tr>
</foreach>
<tr>
    <td colspan="2">
      <button class="btn btn-xs btn-danger" onclick="return tijiao(&#39;del&#39;)">
        <i class="icon-trash bigger-110"></i>
        删除
      </button>
     </td>
  </tr>
Copy after login

The javascript method deleted above is written like this:

<script type="text/javascript">
function tijiao(type){
  if(type == &#39;del&#39;){
    $(&#39;#my_form&#39;).attr(&#39;action&#39;,"{:U(&#39;Admin/Brand/brand_del&#39;)}");
  }else if(type == &#39;sort&#39;){
    $(&#39;#my_form&#39;).attr(&#39;action&#39;,"{:U(&#39;Admin/Brand/brand_sort&#39;)}");
  }
  return true;
}
</script>
Copy after login

Additional: In fact, it is best to use this data to determine whether the file has been uploaded:

$_FILES[&#39;input_name&#39;][&#39;size&#39;]
Copy after login

Is it greater than zero;

Recommended: "The latest 10 thinkphp video tutorials"

The above is the detailed content of Detailed explanation of how ThinkPHP implements image uploading. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template