php + WebUploader Realization of Picture Batch Upload Function

  • 2021-12-09 08:37:39
  • OfStack

1.webuploader

webuploader is mainly used for uploading files, supporting batch uploading and picture preview. Picture preview is to generate base64 data from pictures and use it directly in labels, so the effect that can be achieved is that you can see the uploading effect first without really uploading pictures. For more specific introduction, you can look at the official website of webuploader. I think that reading official website documents is the most direct way to learn. webuploader official website, incidentally, webuploader is maintained by Baidu Fex Team team.

2. webuploader upload principle

1. PHP+HTML form upload file

Before talking about this, you need to know the file upload mode of php under 1. Upload is divided into two parts

First create the form through html and add the


<input type='file' name='xxx'>

The file upload tab, click the upload submit button, you can upload the file to the server.

2. On the server side, the received uploaded files will be stored in the temporary folder specified by php. By using the built-in function move_uploaded_file () of PHP, the temporary files can be moved to the target folder you want. This process can rename the files and judge whether the size meets the conditions, so the upload is completed.

Complete php form upload case, you can see w3school this article, here is not cumbersome. PHP+HTML Form Upload File

2. webuploader upload principle

Using php+html form upload can complete the file upload work, but there are disadvantages,

You must submit the entire page when uploading the file, so that the page will be refreshed There is no way to preview the picture when uploading the picture, so sometimes uploading the wrong picture will not know until the page is refreshed after the picture is really uploaded.

webuploader solves these two problems. webuploader uses ajax technology to submit forms. When uploading, it does not need to submit pages. It can use event monitoring mechanism to monitor uploaded results, give feedback in pages, and preview pictures. It takes only a few steps to upload pictures using webuploader:

Foreground HTML page configuration webuploader The background server PHP page accepts the uploaded pictures of webuploader and then processes them. After processing the picture in the background, return the result of json data to the foreground The foreground will give feedback after receiving it.

Here is one point, the background PHP receiving and processing pictures is basically the same as PHP+HTML form uploading.

3. Configuration and use of webuploader

All configuration parameters and usage methods can be viewed in official documents. webuploader official website, in webuploader github warehouse, there are some example cases for reference. example

My Running Environment: php5.6 + nginx+macOS

My Folders Directory

index.php upload_img.php mywebupload.js webuploader/ uploads/

1. Configure webupload on the foreground HTML page

Mainly do the following steps:

Related js and css packets introducing webuploader Create an HTML tag Create an js file and initialize webuploader. The following is the whole page code. The webuploader folder is moved down on github. Then I used jquery to enhance the page experience.

index.html


<!doctype html>
<html lang="cn">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
  <title>WebUploader Demo </title>
  <link rel="stylesheet" type="text/css" href="webuploader/css/webuploader.css" />
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" />
  <link rel="shortcut icon" href="favicon.ico">
</head>
<body>

  <div id="imgPicker"> Select a file </div>
  <button class="btn btn-primary btn-upload"> Upload </button>
  <div class="img-thumb"></div>
  <div class="result"></div>
  
<!--jquery 1.12-->
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<!--bootstrap Core js Documents -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
<!--webuploader js-->
<!--<script type="text/javascript" src="static/jquery.js"></script>-->
<script type="text/javascript" src="webuploader/dist/webuploader.min.js"></script>
<script type="text/javascript" src="mywebupload.js"></script>
</body>
</html>

mywebupload.js


$(function(){

  /*
   *   Configure webuploader
   */

  var imgUploader = WebUploader.create({
    fileVal: 'img', //  Equivalent to input Labeled name Property, used in the background PHP Object that receives the uploaded file field
    swf: './webuploader/dist/Uploader.swf', // swf File path 
    server: './upload_img.php', //  File receiving server. 
    fileNumLimit: 10,  //  Restrictions on uploading files 
    pick: {
      id : '#imgPicker',  // 
      multiple : true      //  Support multi-file upload 
    },
    //  Only upload pictures 
    accept: {
      title: 'Only Images',
      extensions: 'gif,jpg,jpeg,bmp,png',
      mimeTypes: 'image/jpg,image/jpeg,image/png,image/gif,image/bmp'
    },
    auto: false,  //  Whether to upload the file automatically after adding it, I set the false Later, I will use my own upload button to upload 
    resize: false  //  Uncompressed image,  Default if yes jpeg The file is compressed before uploading 1 Upload it again! 
  });
  
  /*
   *   Set the click event of the upload button 
   */
  $('.btn-upload').click(function(){
    imgUploader.upload();  // webuploader Built-in upload Function to start webuploader Upload of   
  });
  
  /*
   *   Configure webuploader Event listening of  
   */
  
  //  When a picture file is added to the upload queue, 
  imgUploader.on('fileQueued', function (file) {
    addImgThumb(file);
  });
  
  //  Production picture preview 
  function addImgThumb(file){
    imgUploader.makeThumb(file, function(error, ret){
      if(!error){
        img = '<img alt="" src="' + ret + '" />';
        $('.img-thumb').append(img);
      }else{
        console.log('making img error');
      }
    },1,1);
  }
  
  imgUploader.on('uploadSuccess'), function(file, response){
    // response  It's backstage upload_img.php Data returned 
    if(response.success){
      $('.result').append('<p>' + file.name + ' Upload succeeded </p>')
    }else{
      $('.result').append('<p>' + response.message + '</p>')
    }
  });
})

2. Background PHP page handles uploaded files

There are several points to pay attention to here:

1 background processing php file name must be the same as webuploader configuration 1.

2 Upload folder remember to set the permissions, linux can use chmod to modify the folder permissions, otherwise it will lead to upload failure.

The way I deal with it here is relatively simple. If you have any questions, you can leave me a message.

upload_img.php


<?php
  $field = 'img';  //  Correspondence webupload Set in fileVal
  
  $savePath = './uploads/';    //  Pay attention to the settings here uploads Permissions for folders 
  $saveName = time() . uniqid() . '_' . $_FILES[$field]['name']; //  Rename a file 
  $fullName = $savePath . $saveName; 
  
  if (file_exists($fullName)) {
    $result = [
      'success'=>false, 
      'message'=>' A file with the same file name already exists '
    ];
  }else{
    move_uploaded_file($_FILES[$field]["tmp_name"], $fullName);
    $result = ['success'=>true, 'fullName'=>$fullName];
  }
  
  return json_encode($result); //  Package the results into json Format return 
?>

The above is the whole content of webuploader. For more parameters and events of webuploader, please refer to the official website of webuploader. I hope you can leave more messages and exchange corrections.

Summarize


Related articles: