Analysis of TP5 framework to upload multiple images

Time:2021-3-3

In this paper, an example of TP5 framework to upload multiple images is described. The details are as follows:

1. Renderings(every time you click Add option, a new file box will be created to add a new picture.)

2、view

<! -- don't forget to import the jQuery file -- >
<! -- post value transfer mode and file transfer protocol must be added with -- >
<input type="file" name="image[]">
< input type = button "name = add" value = + add option ">
< button type = "submit" name = "submit" > Add < / button >
 
<script type="text/javascript">
  $("#add").click(function(){
    $(this).before('<input type="file" name="image[]">');
  });
</script>

3、controller

//Receive image array from view
$image=request()->file('image');
 
//Instantiate the model and call the method of adding pictures in it
$details = new Details();
$info = $details->add($image);
if($info === 1)
{
  Return 'operation successful';
}
else
{
  Return 'operation failed';
}

4、model

//Add the received $image foreach traversal
foreach($image as $image)
{
  //Instantiation model
  $details = new Details();
  $time=date('Ymd',time());
  //Defines the current timestamp as the file name
  $filename=time();
  //Check whether there is a folder for storing pictures
  if(!file_exists(ROOT_PATH . 'public' . DS .'static'. DS .'img'))
  {
    //Create file
    mkdir(ROOT_PATH . 'public' . DS .'static'. DS .'img');
  }
  //Upload pictures
  $info=$image->move(ROOT_PATH . 'public' . DS .'static'. DS .'img'.DS.$time,$filename);
  //Store the image path in the database
  $details->url = $time.DS.$info->getFileName();
  $details->allowField(true)->save();
}
return 1;

5、over over over

For more information about ThinkPHP, interested readers can check out the following topics: introduction to ThinkPHP, summary of operation skills of ThinkPHP template, summary of common methods of ThinkPHP, introduction to CodeIgniter, CI (CodeIgniter) framework advanced course, Zend framework introduction course and PHP template technology summary.

I hope this article will be helpful to the design of PHP program based on ThinkPHP framework.