search
HomeWeb Front-endJS TutorialBasic use of file upload component WebUploader
Basic use of file upload component WebUploaderMay 08, 2020 am 09:21 AM
jsFile Upload

1. Origin

The company’s website community has a picture upload function. Since the website has been around for some years, the upload process was divided into categories based on whether the client supported flash or not. Two kinds of logic. If flash is supported, use the SWFuploader upload component to upload files. This has a better user experience. If flash is not supported, use ordinary input tags to upload. This method has incomplete functions and a poor experience. However, since the Chrome browser does not support flash by default, most of the time users use input tags to upload, and the upload experience is not good, so we decided to use Baidu's webuploader upload component to replace the original upload component. If you find some problems during the replacement process, record the areas that need attention.

2. Notes on using WebUploader

In fact, the general usage of third-party js plug-ins is similar. They basically import resource files, initialize plug-in objects according to configuration, and use objects. Methods or listening events complete specific functions, and webuploader is similar.

JS import resource file

<link href="../JS/webuploader/webuploader.css" rel="stylesheet" />
<script src="../JS/webuploader/jquery-1.12.4.min.js"></script>
<script src="../JS/webuploader/webuploader.js"></script>

You need to import the css file, jquery.js and webuploader.js files of wepuploader.

The css file is the style file of the upload button generated by webuploader for you. If you are not satisfied with the default style, first, you can modify the css yourself to meet your requirements. Another method is to prepare your own css file, then modify the source code of webuploader.js, and then specify the class of the button, mouseenter, mouseleave class, etc. The webuploader.js code location is as follows:

button.addClass(&#39;webuploader-pick&#39;);
                //button.addClass(&#39;btn&#39;);
                //button.addClass(&#39;btn-default&#39;);
    
                me.on( &#39;all&#39;, function( type ) {
                    var files;
    
                    switch ( type ) {
                        case &#39;mouseenter&#39;:
                            button.addClass(&#39;webuploader-pick-hover&#39;);
                            break;
    
                        case &#39;mouseleave&#39;:
                            button.removeClass(&#39;webuploader-pick-hover&#39;);
                            break;
    
                        case &#39;change&#39;:
                            files = me.exec(&#39;getFiles&#39;);
                            me.trigger( &#39;select&#39;, $.map( files, function( file ) {
                                file = new File( me.getRuid(), file );
    
                                // 记录来源。
                                file._refer = opts.container;
                                return file;
                            }), opts.container );
                            break;
                    }
                })

Since webuploader is based on jquery, jquery.js needs to be imported, and the jquery version must be greater than 1.10. The trick is that because the website is old, prototype.js was used to perform various operations before. In order to transfer $ usage rights to prototype, jQuery.noConflict() is also required. Of course, this operation is generally not needed.

The version of webuploader.js I use here is 0.1.2. I used 0.1.5 before. However, when performing flash upload in 0.1.5, if the server does not return a string in json format, the webuploader.js code will report an error and the client will not receive the return information. What our server returns is an ordinary string, so there is no other way but to use 0.1.2.

Initialize the webuploader object

Before initializing the object, because the upload button is generated by webuploader itself, first prepare the parent tag of the upload button, and webuploader will generate the upload tag within the tag. It can be div, span, etc. What I use is span:

<span id="uploadImage"></span>

Then I can initialize the webuploader object. The js code is as follows:

    var uploader = WebUploader.create({
        //是否允许重复的图片
        duplicate: true,
        auto: false, // 选完文件后,是否自动上传
        swf: &#39;../JS/webuploader/Uploader.swf&#39;, // swf文件路径
        server: "/upload.html", // 文件接收服务端
        pick: { id: "#uploadImage", innerHTML: "本地上传图片" }, // 选择文件的按钮。可选
        // 只允许选择图片文件。
        accept: {
            title: &#39;Images&#39;,
            extensions: &#39;gif,jpg,jpeg,bmp,png&#39;,
            mimeTypes: &#39;image/*&#39;
        },
        //线程数
        threads: 1,
        //单个文件大小限制
        fileSingleSizeLimit: 2000,
        //上传文件数量限制
        fileNumLimit:10,
        //上传前不压缩
        compress:false,
    });

The WebUploader.create() method generates the webuploader object (it seems that there are other methods to generate it, but This is not the point), just pass in the configuration object.

The server attribute specifies the server address for file upload.

The pick attribute specifies the upload button, and the id specifies which button through jquery's selector (it does not have to be the id selector of #)

The swf attribute specifies where to load the swf file when flash is enabled ( Webuploader is internally compatible with flash and h5, we don't need to pay attention to which method it uses)

auto After selecting the file, whether to automatically upload it, I don't use automatic upload here, because after selecting the file, I need to upload it on the UI Do a few things and then I'll manually specify to start uploading.

The configuration needs to pay attention to the above attributes. There are many other attributes, some of which have been commented in the above js. For others that are not included, you can refer to the official WebUploader documentation.

Listening to webuploader events

After configuring the above, you can see your upload button on the page, but the above is not the point. The key to using webuploader flexibly is to handle a series of events triggered by webuploader during the uploading of images. According to our business requirements, I mainly monitored the following events:

    //当有一批文件加载进队列时触发事件
    uploader.on("filesQueued", webFilesQueued);
    //当有一批文件加载进队列时触发事件
    //uploader.on("fileQueued", webFilesQueued);
    //单个文件开始上传
    uploader.on("uploadStart", uploadStart);
    //单个文件上传成功
    uploader.on("uploadSuccess", uploadSuccess);
    //单个文件上传过程中
    uploader.on("uploadProgress", uploadProgress);
    //所有文件上传结束
    uploader.on("uploadFinished", uploadComplete);
    //图片校验不通过时
    uploader.on("error", webFileQueueError);
    //上传出错时
    uploader.on("uploadError",webUploadError);

webuploader will select the file you select through the file dialog box The picture (can be one or multiple pictures) is added to a queue, and then all files in the queue are uploaded (note that if the thread you configure is greater than 1, webuploader supports multi-threaded upload).

filesQueued This event is triggered when a batch of files are loaded into the queue. At this time, the files have not yet started to be uploaded. You can perform some business logic. For example, I need to determine how many pictures have been uploaded this time, and then dynamically generate so many picture boxes on the page. After executing the business logic, I need to manually specify to start uploading (because I configured auto: false) and execute loader.startUpload() (if it is uploaded automatically, there is no need to manually execute this method), then all the pictures in the queue at this time will be The upload has started.

fileQueued is similar to filesQueued, but this is an event triggered when a single file is queued. This event will be triggered multiple times when multiple images are selected at one time.

uploadStart Event triggered when a single file starts to be uploaded.

uploadProgress is an event triggered during a single file upload. In the callback method, you can receive the percentage of upload. Using this percentage, we can dynamically display the upload progress bar.

uploadSuccess 单个文件上传成功触发的事件,在回调方法内你可以接收到服务器端返回的数据以及当前是哪个file对象上传成功,目测通过file对象可以获取到图片的缩略图对象(webuploader前端帮我们生成的),可以在UI上显示缩略图等等逻辑(根据自己的业务要求决定。。。。)。

function uploadSuccess(file, serverData) {
    doSomeThing();
}

uploadFinished 队列中所有文件上传成功时触发的事件,具体回调方法视业务逻辑决定。

error 图片在加入队列之前会进行校验,看大小、格式等等是否满足配置要求,校验不通过触发的事件,你可以在UI上弹窗提示用户

uploadError 这里图片校验通过,加入了队列,并且开始上传到服务器,如果服务器或者网络有问题导致出错触发的事件,可以提示用户上传不成功。

三、一些杂项

按照以上方法应该一般的上传问题都可以解决,不过这次替换过程中还遇到一些问题,记录如下:

上传总数量限制

在前端我们有总数量的限制,但是配置时fileNumLimit:10属性指的并不是总数量10张,而是该次对话框你选择的文件数量,如果文件对话框内你选了12张,那么webuploader也会上传10张,但是后面的两张会丢弃掉。如果想对总数量限制一种方法是修改webuploader.js的源码:

 uploader.on( &#39;beforeFileQueued&#39;, function( file ) {
                //实时获得上传限制的文件总数
                max = this.options.fileNumLimit;
                if ( count >= max && flag ) {
                    flag = false;
                    this.trigger( &#39;error&#39;, &#39;Q_EXCEED_NUM_LIMIT&#39;, max, file );
                    setTimeout(function() {
                        flag = true;
                    }, 1 );
                }
                return count >= max ? false : true;
            });
    
            uploader.on( &#39;fileQueued&#39;, function() {
                count++;
            });
    
            uploader.on( &#39;fileDequeued&#39;, function() {
                count--;
            });
    
            uploader.on( &#39;uploadFinished&#39;, function() {
                //count = 0; 限制总数量,而不是限制一次的文件数量
            });

数量校验结束后count会清0,把这个注释掉(上面js倒数第二行被注释的代码)那么fileNumLimit就是总数量了。

还有一种方法是webuploader会记录上传成功的文件数,自己拿到这个数来进行判断就行了。

chrome浏览器不能连续选择相同图片

连续上传同一图片时在chrome浏览器上总是不触发入队的事件,刚开始以为是配置的duplicate属性是false,后来发现duplicate属性是正确的true。这是chrome的特性,选择文件对话框关闭的时候会将input标签的value属性设置为这张图片的hash值?,如果input已经有了value属性(上一张图片的),并且和这一张的相同,那么将不触发change事件,也就是不上传了。解决方法:

function uploadComplete(file) {
        //解决chrome浏览器不能连续两次上传相同图片的bug k----------
        if ($("uploadImageDiv").select("input").length > 0) {
            $("uploadImageDiv").select("input")[0].value = "";
        }
        //解决chrome浏览器不能连续两次上传相同图片的bug k----------
}

监听上传完成事件,把input标签的value设为空就行了。

推荐教程:《JS教程

The above is the detailed content of Basic use of file upload component WebUploader. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:jianshu. If there is any infringement, please contact admin@php.cn delete
如何使用JS和百度地图实现地图平移功能如何使用JS和百度地图实现地图平移功能Nov 21, 2023 am 10:00 AM

如何使用JS和百度地图实现地图平移功能百度地图是一款广泛使用的地图服务平台,在Web开发中经常用于展示地理信息、定位等功能。本文将介绍如何使用JS和百度地图API实现地图平移功能,并提供具体的代码示例。一、准备工作使用百度地图API前,首先需要在百度地图开放平台(http://lbsyun.baidu.com/)上申请一个开发者账号,并创建一个应用。创建完成

js字符串转数组js字符串转数组Aug 03, 2023 pm 01:34 PM

js字符串转数组的方法:1、使用“split()”方法,可以根据指定的分隔符将字符串分割成数组元素;2、使用“Array.from()”方法,可以将可迭代对象或类数组对象转换成真正的数组;3、使用for循环遍历,将每个字符依次添加到数组中;4、使用“Array.split()”方法,通过调用“Array.prototype.forEach()”将一个字符串拆分成数组的快捷方式。

如何使用JS和百度地图实现地图热力图功能如何使用JS和百度地图实现地图热力图功能Nov 21, 2023 am 09:33 AM

如何使用JS和百度地图实现地图热力图功能简介:随着互联网和移动设备的迅速发展,地图成为了一种普遍的应用场景。而热力图作为一种可视化的展示方式,能够帮助我们更直观地了解数据的分布情况。本文将介绍如何使用JS和百度地图API来实现地图热力图的功能,并提供具体的代码示例。准备工作:在开始之前,你需要准备以下事项:一个百度开发者账号,并创建一个应用,获取到相应的AP

如何使用JS和百度地图实现地图多边形绘制功能如何使用JS和百度地图实现地图多边形绘制功能Nov 21, 2023 am 10:53 AM

如何使用JS和百度地图实现地图多边形绘制功能在现代网页开发中,地图应用已经成为常见的功能之一。而地图上绘制多边形,可以帮助我们将特定区域进行标记,方便用户进行查看和分析。本文将介绍如何使用JS和百度地图API实现地图多边形绘制功能,并提供具体的代码示例。首先,我们需要引入百度地图API。可以利用以下代码在HTML文件中导入百度地图API的JavaScript

js中new操作符做了哪些事情js中new操作符做了哪些事情Nov 13, 2023 pm 04:05 PM

js中new操作符做了:1、创建一个空对象,这个新对象将成为函数的实例;2、将新对象的原型链接到构造函数的原型对象,这样新对象就可以访问构造函数原型对象中定义的属性和方法;3、将构造函数的作用域赋给新对象,这样新对象就可以通过this关键字来引用构造函数中的属性和方法;4、执行构造函数中的代码,构造函数中的代码将用于初始化新对象的属性和方法;5、如果构造函数中没有返回等等。

用JavaScript模拟实现打字小游戏!用JavaScript模拟实现打字小游戏!Aug 07, 2022 am 10:34 AM

这篇文章主要为大家详细介绍了js实现打字小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

php可以读js内部的数组吗php可以读js内部的数组吗Jul 12, 2023 pm 03:41 PM

php在特定情况下可以读js内部的数组。其方法是:1、在JavaScript中,创建一个包含需要传递给PHP的数组的变量;2、使用Ajax技术将该数组发送给PHP脚本。可以使用原生的JavaScript代码或者使用基于Ajax的JavaScript库如jQuery等;3、在PHP脚本中,接收传递过来的数组数据,并进行相应的处理即可。

js是什么编程语言?js是什么编程语言?May 05, 2019 am 10:22 AM

js全称JavaScript,是一种具有函数优先的轻量级,直译式、解释型或即时编译型的高级编程语言,是一种属于网络的高级脚本语言;JavaScript基于原型编程、多范式的动态脚本语言,并且支持面向对象、命令式和声明式,如函数式编程。

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尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),