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

Detailed explanation of how ThinkPHP implements image uploading

Aug 12, 2021 pm 02:08 PM
thinkphp upload picture

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

WeChat applet implements image upload function WeChat applet implements image upload function Nov 21, 2023 am 09:08 AM

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

How is the performance of thinkphp? How is the performance of thinkphp? Apr 09, 2024 pm 05:24 PM

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

See all articles