search
HomeBackend DevelopmentPHP Tutorialphp+WebUploader image batch upload

php+WebUploader image batch upload

1.webuploader

webuploader is mainly used to upload files and supports batch uploads and image previews. Preview is to generate base64 data from the image and use it directly in the php+WebUploader image batch upload tag, so the effect that can be achieved is that you can see the effect of uploading the image before actually uploading it. For more detailed introduction, you can go to the official website of webuploader. I always believe that reading the official website documents is the most direct way to learn. webuploader official website, by the way, webuploader is maintained by the Baidu Fex Team team.

2. Webuploader upload principle

1. PHP HTML form upload file

Before talking about this, you need to understand the file upload method of PHP. The upload is divided into two parts.

  1. First create the <form></form> form through html, and add the file upload tag of

<input>

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

  1. At the server side, the received uploaded file will be stored in the temporary folder specified by PHP. Use PHP's built-in function move_uploaded_file(). Move the temporary file to the target folder you want. This process can rename the file, size it to determine whether it meets the conditions, etc. Then the upload is complete.

For a complete PHP form upload case, you can read this article by w3school, so I won’t go into details here. PHP HTML form upload file

2. Webuploader upload principle

Using PHP HTML form upload can complete the file uploading work, but it has shortcomings,

  1. When uploading a file, you must submit the entire page, so that the page will be refreshed

  2. There is no way to preview the image when uploading it, so sometimes you have to wait until the wrong image is uploaded You won’t know until you refresh the page after the picture is actually uploaded.

webuploader solves these two problems. Webuploader uses ajax technology to submit the form. There is no need to submit the page when uploading. You can use the event listening mechanism to monitor the upload results and make decisions on the page. feedback, and can also do picture preview. Using webuploader to upload images only requires a few steps:

  1. The front-end HTML page configures webuploader

  2. The background server PHP page accepts images uploaded by webuploader. Then process it.

  3. After processing the image in the background, the result of returning json data is sent to the front desk.

  4. The front desk receives the json data and gives feedback.

Let me talk about it here. The background PHP receiving and processing images is basically the same as PHP HTML form upload.

3. Configuration and use of webuploader

You can view the official documents for all configuration parameters and usage methods. webuploader official website, there are some example cases in the webuploader github warehouse 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. Front-end HTML page configuration webupload

Mainly do the following steps:

  1. Introduce the relevant js and css packages of webuploader

  2. Create HTML tags

  3. Create a js file and initialize webuploader. The following is the entire page code, The webuploader folder was moved entirely from github, and then I used jquery to enhance the page experience.

index.html

nbsp;html>


    <meta>
    <meta>
    <title>WebUploader演示</title>
    <link>
    <link>
    <link>



    <div>选择文件</div>
    <button>上传</button>
    <div></div>
    <div></div>
    
<!--jquery 1.12-->
<script></script>
<!--bootstrap核心js文件-->
<script></script>
<!--webuploader js-->
<!--<script type="text/javascript" src="static/jquery.js"></script>-->
<script></script>
<script></script>

mywebupload.js

$(function(){

    /*
     *   配置webuploader
     */

    var imgUploader = WebUploader.create({
        fileVal: 'img',  // 相当于input标签的name属性,用于后台PHP识别接收上传文件的field
        swf: './webuploader/dist/Uploader.swf',  // swf文件路径
        server: './upload_img.php',  // 文件接收服务端。
        fileNumLimit: 10,   // 上传文件的限制
        pick: {
            id : '#imgPicker',   // 
            multiple : true           // 是否支持多文件上传
        },
        //  只允许上传图片
        accept: {
            title: 'Only Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/jpg,image/jpeg,image/png,image/gif,image/bmp'
        },
        auto: false,    // 添加文件后是否自动上传上去,我设置了false,后面我会利用自己的上传按钮上传
        resize: false   // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
    });
    
    /*
     *   设置上传按钮的单击事件
     */
    $('.btn-upload').click(function(){
        imgUploader.upload();   // webuploader内置的upload函数,启动webuploader的上传    
    });
    
    /*
     *   配置webuploader的事件监听 
     */
    
    // 当图片文件被添加到上传队列中
    imgUploader.on('fileQueued', function (file) {
        addImgThumb(file);
    });
    
    // 生产图片预览
    function addImgThumb(file){
        imgUploader.makeThumb(file, function(error, ret){
            if(!error){
                img = '<img  src="/static/imghwm/default1.png" data-src="' + ret + '" class="lazy" alt="php+WebUploader image batch upload" >';
                $('.img-thumb').append(img);
            }else{
                console.log('making img error');
            }
        },1,1);
    }
    
    imgUploader.on('uploadSuccess'), function(file, response){
        // response 是后台upload_img.php返回的数据
        if(response.success){
            $('.result').append('<p>' + file.name + '上传成功</p>')
        }else{
            $('.result').append('<p>' + response.message + '</p>')
        }
    });
})

2. The background PHP page processes uploaded files

There are two things to note here Point:

  1. The file name of the php file processed in the background must be the same as when the webuploader is configured.

  2. Remember to set the permissions of the uploaded folder. Linux can use chmod to modify the folder permissions, otherwise the upload will fail.

My handling method here is relatively simple. If you have any questions, please leave me a message.

upload_img.php

<?php     $field = &#39;img&#39;;   // 对应webupload里设置的fileVal
    
    $savePath = &#39;./uploads/&#39;;       // 这里注意设置uploads文件夹的权限
    $saveName = time() . uniqid() . &#39;_&#39; . $_FILES[$field][&#39;name&#39;]; //  为文件重命名
    $fullName = $savePath . $saveName;  
    
    if (file_exists($fullName)) {
        $result = [
            &#39;success&#39;=>false, 
            'message'=>'相同文件名的文件已经存在'
        ];
    }else{
        move_uploaded_file($_FILES[$field]["tmp_name"], $fullName);
        $result = ['success'=>true, 'fullName'=>$fullName];
    }
    
    return json_encode($result);  // 将结果打包成json格式返回
?>

The above is the entire content of webuploader. For more parameter configurations and events of webuploader, please refer to the official website of webuploader. I hope everyone will leave more messages to exchange comments and corrections.

For more PHP related technical articles, please visit the PHP Tutorial column to learn!

The above is the detailed content of php+WebUploader image batch upload. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools