Thinkphp5 framework combined with plupload to achieve image batch upload function example

Time:2021-2-25

In this paper, an example is given to show how thinkp5 framework combined with plupload can achieve the function of uploading pictures in batches. The details are as follows:

Add a new directory uploader and a new class uploads in the extend directory

<?php
namespace uploader;
 
class Uploads {
 public static function upfile($file, $path = 'images', $add_domain = false) {
  $res = ['errno '= > 1,' errmsg '= >'upload image error'];
  $data = '';
  if(!empty($file)) {
   //Upload root
   $file_path = 'uploads/';
   //If the path is passed, add the path
   if(!empty($path)) {
    $file_path .= $path .'/';
   }
   if (!file_exists($file_path)) {
    @mkdir($file_path);
   }
   //Upload
   $info = $file->move($file_path);
   //Get suffix
   $ext = strtolower($info->getExtension());
   //Judge whether the suffix is legal
   $exts = ['jpg', 'png', 'gif', 'jpeg', 'mp4', 'avi', '3gp'];
   if(in_array($ext, $exts)) {
    $save_name = $info->getSaveName();
    $save_path = "/" . $file_path . $save_name;
    if($add_domain) {
     $save_path = "http://www.localhost.com/" . $file_path . $save_name;
    } 
    $res = ['errno' => 0, 'data' => $save_path];
   } else {
    $res = ['errno' => 1, 'errmsg' => $ext];
   }
  } else {
   $res = ['errno '= > 1,' errmsg '= >' please select a picture! '];
  }
  
  return $res;
 }
}
?>

use

<?php
 
namespace app\backend\controller;
 
use think\Controller;
use think\Request;
use uploader\Uploads;
 
class Upload extends Controller
{
 public function upload(Request $request) {
  $files = $request->file("file");
  $updir = $request->post('updir');
  $res = Uploads::upfile($files, $updir);
  return json_encode($res);
 }
 
 public function del_upload(Request $request) {
  $res = ['errno '= > 1,' errmsg '= >' delete failed '];
  $filename = $request->post('filename');
  if(!empty($filename)) {
   @unlink($_SERVER['DOCUMENT_ROOT'] . $filename);
   $res = ['errno' => 0, 'errmsg' => $filename];
  }
  return json_encode($res);
 }
 
}
 
?>

Front end JS

var image_ Files = new array(); // upload multiple images and save them temporarily
$(document).ready(function() {
 $('.media-picker').each(function() {
  var el = $(this);
  var elbtn = el.find('.media-picker-button');
  var multi_selection = false;
  var inputField = el.find('input[type=hidden]');
  //Upload multiple files
  if(elbtn.attr('data-multiple') == 'multiple') {
   multi_selection = true;
  }
  //Upload directory
  var upload_path = inputField.attr('upload-path');
  var uploader = new plupload.Uploader({
   runtimes : 'html5,flash,silverlight,html4',
   browse_button : elbtn.attr('data-id') + '_uploader', 
   multi_selection: multi_selection,
   auto_start: true,
   flash_swf_url : '../plugins/plupload/js/Moxie.swf',
   silverlight_xap_url : '../plugins/plupload/js/Moxie.xap',
   url : '/backend/upload',
   
   filters: {
    mime_ Types: [// only images and zip, rar files can be uploaded
    { title : "Image files", extensions : "jpg,jpeg,gif,png,bmp" }, 
    { title : "Video files", extensions : "mp4,3gp" }
    ],
    max_ file_ Size: '10MB' // only 10MB files can be uploaded
    prevent_ Duplicates: false // duplicate files are not allowed
   },
 
   init: { 
    PostInit: function() {},
 
    BeforeUpload: function(up, file) {
     up.setOption('multipart_params', {'updir': upload_path})
    },
 
    FilesAdded: function(up) {
     up.start (); // upload directly after selecting
    },
 
    FileUploaded: function(up, file, info) {
     if (info.status == 200)
     {
      var file_type = file.type;
      var is_image = file_type.indexOf('image');
      var is_video = file_type.indexOf('video');
      //Parsing the returned data
      var result = JSON.parse(info.response);
      var img_list = "";
      if(result.errno == 0) {
       //Returned image upload results
       var file_name = result.data; 
       if(multi_selection) {
        //Multi image upload does not consider video
        if (is_image > -1) {
         //Save to temporary array
         image_files.push(file_name);
         inputField.val(JSON.stringify(image_files));
         for (var i = 0; i < image_files.length; i++) {
          img_list += "<li><img src='"+image_files[i]+"' /><span class='delete-image'>✖</span><p>"+image_files[i]+"</p></li>";
         }
        }
       } else {
        inputField.val(file_name);
        if (is_image > -1) {
         img_list = "<li><img src='"+result.data+"' /><span class='delete-image'>✖</span><p>"+result.data+"</p></li>";
        }
        if (is_video > -1) { 
         img_list = "<li><video controls src='"+result.data+"'></video><span class='delete-image'>✖</span><p>"+result.data+"<p></li>";
        }
       }
       el.find('.image-list').html(img_list);
      } else {
       alert(result.errmsg);
      }
     }
     else
     {
      alter(info.response);
     } 
    },
 
    Error: function(up, err) {
     alert(err.response);
    }
   }
  })
  uploader.init();
 
 
  //Delete
  if (multi_selection) {
   el.on('click', '.delete-image', function() {
    var file_name = inputField.val();
    var elDel = $(this);
    //Get the file name
    var current_file_name = elDel.next('p').html();
    //Delete当前的父级li
    elDel.parent().remove();
    //Reassign array
    var new_image_files = new Array();
    if (image_files != '') {
     new_image_files = image_files;
    } else {
     new_image_files = $.parseJSON(file_name);
    }
    //Remove the current value from the array
    for(var i in new_image_files) {
     if(new_image_files[i] == current_file_name) {
      new_image_files.splice(i,1);
      break;
     }
    }
    $.ajax({
      type: "POST",
      url: "/backend/del_upload",
      data: "filename=" + current_file_name,
      success: function(msg) {
        console.log(msg)
      }
    });
    inputField.val(JSON.stringify(new_image_files));
   });
  } else {
   el.on('click', '.delete-image', function(){
    //The display value is empty
    var file_name = inputField.val();
    el.find('.image-list').html('');
    inputField.val('');
    $.ajax({
     type: "POST",
     url: "/backend/del_upload",
     data: "filename=" + file_name,
     success: function(msg) {
       console.log(msg)
     }
    });
   });
  }
 })
})

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.

Recommended Today

Practice analysis of rust built-in trait: partialeq and EQ

Abstract:Rust uses traits in many places, from simple operator overloading to subtle features like send and sync. This article is shared from Huawei cloud community《Analysis of rust built-in trait: partialeq and EQ》Author: debugzhang Rust uses traits in many places, from simple operator overloading to subtle features like send and sync. Some traits can be automatically […]