Home  >  Article  >  Backend Development  >  How to implement image upload operation in ThinkPHP

How to implement image upload operation in ThinkPHP

不言
不言Original
2018-06-06 16:11:211399browse

This article mainly introduces the method of ThinkPHP to implement image upload operation, and analyzes in detail the specific steps and related operation techniques of thinkPHP image upload operation. Friends in need can refer to the following

The examples of this article describe the implementation of ThinkPHP How to upload images. Share it with everyone for your reference. The details are as follows:

Let’s go directly to the example, which includes uploading a single image file, uploading multiple image files, and deleting some files. When deleting the database, just delete it. The file path in the database, instead of deleting the files in the server together, causing the server to explode,

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;
}
?>

In fact, no matter which file is uploaded, 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>

How to process uploaded files in the controller (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("添加失败!证件可能已存在");
}

The UNLINK_PATH variable is in ThinkPHP It is defined in the config file and comes from 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,  //是否开启话题审核
);

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

When displaying the image above, use the absolute path of the HTTP protocol The pictures are spliced ​​together to display;

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

Remember to call upload in ThinkPHP , the uploadone method returns only the storage location of the uploaded file under the upload folder, "'2016-09-02/57c94e71f0916.png'" (I think this is also the storage location)

So whether it is deleted or displayed, Need to use C method to splice it

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("删除运营商品牌失败!");
    }
}

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

Multiple selection, and passed to the corresponding column How is the value of the ID implemented?

<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>

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>

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;]

Is it greater than zero;

I can see a bigger world.

Related recommendations:

thinkPHP implemented Example of three-level linkage function in provinces and municipalities

ThinkPHP implements one-click cache clearing method

ThinkPHP file upload example

The above is the detailed content of How to implement image upload operation in ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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