A webuploader.

Webuploader is mainly used to do file upload, support batch upload and image preview, image preview is to generate base64 data directly in the imageTag is used, so the effect can be achieved without actually uploading the image can see the uploaded effect first. For more details, you can visit the official website of Webuploader. I always believe that reading the official documents is the most direct way to learn.Webuploader official websiteBy the way, Webuploader is maintained by the Baidu Fex Team.

Ii. Webuploader upload principle

1. Upload files in PHP+HTML form

Before we do that, we need to take a look at how PHP uploads files. Uploading is a two-part process

  1. Start with HTML<form>Form, add in the form
<input type='file' name='xxx'>
Copy the code

After clicking the submit button, you can upload the file to the server.

  1. On the server side, the received uploaded files are stored in a PHP designated temporary folder, using PHP’s built-in functionsmove_uploaded_file()“, you can move the temporary file to the desired destination folder, rename the file, size the file to determine whether it meets the requirements, and so on, and upload is complete.

For a complete PHP form upload example, you can see this article from W3School. PHP+HTML form uploads files

2. Webuploader uploads

Using PHP + HTML form upload can complete the file upload work, but there are disadvantages,

  1. When uploading a file, you must submit the entire page so that the page is refreshed
  2. There is no way to preview images, so sometimes uploading the wrong image will not be known until you refresh the page after the image is actually uploaded.

Webuploader solves both of these problems. Webuploader uses Ajax technology to submit forms without submitting pages. Webuploader uses event listening mechanism to listen to the upload results, give feedback on the page, and also preview images. Uploading images using Webuploader also takes just a few steps:

  1. The front HTML page is configured with webuploader
  2. The backend server PHP page accepts uploaded images from Webuploader and processes them.
  3. After processing the image, the background returns the result of JSON data to the foreground
  4. The foreground receives the JSON data and gives feedback.

For one thing, background PHP accepts and processes images in the same way that PHP+HTML forms upload.

3. Configuration and use of Webuploader

All configuration parameters and usage methods can be viewed in the official file. Webuploader github repository webuploader github repository has some examples for reference. example

My running environment: PHP5.6 +nginx+macOS

The directory of my folder

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

1. Configure Webupload on the front HTML page

Mainly do the following steps:

  1. Introduce webuploader related JS and CSS packages
  2. Creating an HTML tag
  3. Create a JS file and initialize webuploader. Here is the code for the entire page. The webuploader folder was moved from Github and I used jquery to enhance the experience.

index.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/[email protected]/dist/css/bootstrap.min.css" />
    <link rel="shortcut icon" href="favicon.ico">
</head>
<body>

    <div id="imgPicker">Select the file</div>
    <button class="btn btn-primary btn-upload">upload</button>
    <div class="img-thumb"></div>
    <div class="result"></div>
    
<! - the jquery 1.12 - >
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<! Bootstrap core JS file -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/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>
Copy the code

mywebupload.js

$(function(){

    /* * Configure webuploader */

    var imgUploader = WebUploader.create({
        fileVal: 'img'.// The name attribute of the input tag is used by the background PHP to identify the field that receives the uploaded file
        swf: './webuploader/dist/Uploader.swf'.// SWF file path
        server: './upload_img.php'.// File receiving server.
        fileNumLimit: 10.// Upload file limits
        pick: {
            id : '#imgPicker'.// 
            multiple : true           // Whether multiple file uploads are supported
        },
        // Upload images only
        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 files automatically after adding them, I set false, I will use my own upload button later to upload
        resize: false   // Do not compress image, default if jpeg, the file will be compressed before uploading!
    });
    
    /* * Sets the upload button click event */
    $('.btn-upload').click(function(){
        imgUploader.upload();   // Webuploader built-in upload function, start webuploader upload
    });
    
    /* * Configure webuploader event listener */
    
    // When the image file is added to the upload queue
    imgUploader.on('fileQueued'.function (file) {
        addImgThumb(file);
    });
    
    // Create image 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 is the data returned by upload_img.php
        if(response.success){
            $('.result').append('<p>' + file.name + 'Upload successful 

'
)}else{$('.result').append('<p>' + response.message + '</p>')}}); })Copy the code

2. The background PHP page processes the uploaded files

Two points to note here:

  1. The background PHP file name must be the same as the webuploader configuration.
  2. Remember to set permissions for the folder to be uploaded. Linux can use chmod to change folder permissions; otherwise, the upload will fail.

The way I deal with here is relatively simple, you can leave a message to me if there is any problem.

upload_img.php


      
    $field = 'img';   // Corresponds to fileVal set in Webupload
    
    $savePath = './uploads/';       // Set the uploads folder permissions
    $saveName = time() . uniqid() . '_' . $_FILES[$field]['name']; // Rename the 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 result in JSON format and return it
? >
Copy the code

This is all about Webuploader. For more information about webuploader parameters and events, please refer to the official website of Webuploader. I hope you can exchange your comments and make corrections.

If this article is useful to you, please help me to like and share.