Basic use of file upload component WebUploader
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('webuploader-pick'); //button.addClass('btn'); //button.addClass('btn-default'); me.on( 'all', function( type ) { var files; switch ( type ) { case 'mouseenter': button.addClass('webuploader-pick-hover'); break; case 'mouseleave': button.removeClass('webuploader-pick-hover'); break; case 'change': files = me.exec('getFiles'); me.trigger( 'select', $.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: '../JS/webuploader/Uploader.swf', // swf文件路径 server: "/upload.html", // 文件接收服务端 pick: { id: "#uploadImage", innerHTML: "本地上传图片" }, // 选择文件的按钮。可选 // 只允许选择图片文件。 accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' }, //线程数 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( 'beforeFileQueued', function( file ) { //实时获得上传限制的文件总数 max = this.options.fileNumLimit; if ( count >= max && flag ) { flag = false; this.trigger( 'error', 'Q_EXCEED_NUM_LIMIT', max, file ); setTimeout(function() { flag = true; }, 1 ); } return count >= max ? false : true; }); uploader.on( 'fileQueued', function() { count++; }); uploader.on( 'fileDequeued', function() { count--; }); uploader.on( 'uploadFinished', 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to implement file upload using gRPC? Create supporting service definitions, including request and response messages. On the client, the file to be uploaded is opened and split into chunks, then streamed to the server via a gRPC stream. On the server side, file chunks are received and stored into a file. The server sends a response after the file upload is completed to indicate whether the upload was successful.

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:
