Implementation of HTML5 file upload progress bar based on HT for web vector

Source: Internet
Author: User
Tags file upload progress bar

In the HTML, in the file upload process, very no matter under what circumstances are prompted, it is very bad experience, there is no upload users do not know when, uploaded successfully did not. So today's introduction to the content is through the HT for Web vector to implement the HTML5 file upload progress bar. Vector in the " Vector Chart chart embedded HTML5 network topology diagram application " in the article has described the Setcomptype () method of application, today we use the SetImage () method to make full use of the system's defined vector resources to implement the file upload progress bar, Let's start by looking at:


From being able to see, upload a MP4 file to the server and display the current upload progress at the bottom.

Then let's explore the details of the implementation:

First, let's analyze the structure of the progress bar:

1. A background is required. Background

2. A current progress value is required. Value

3. Need a foreground, foreground, based on the current progress value, draw the foreground. Cover the background.

The structure is so simple. Then the next step is the detailed implementation, look at the code:

Ht. Default.setimage (' progress ', {    width:150,    height:12,    comps: [        //Draw background        {            type: ' Rect ',            Rect: {x:0, y:0, width:115, height:12},            background: {func:function (data) {return data.a (' background ');}}        },        //Draw foreground        {            rect: {x:0, y:0, width:115, height:12},            type:function (g, Rect, comp, data , view) {                var width = rect.width, height = rect.height, value = Data.getvalue (),                     forewidth = width/100 * value ;                G.fillstyle = data.a (' foreground ');                G.fillrect (0, 0, forewidth, height);            }        }    ]});

We define a vector object named progress, a vector object consisting of two parts and a background. One is the foreground.

The drawing background uses the data binding method, binds the background property, the drawing foreground is drawn with the method of its own definition type, is an abbreviation of the Setcomptype () method, and the drawing is the drawing width calculated from the value values in data.

The overall design of the vector has been completed. Then we'll use him. See how it works.

var Datamodel = new ht. Datamodel (),    node = new ht. Node (); node.setvalue (0); Node.setimage (' progress '); Node.a (' Background ', ' #5F6870 '); Node.a (' foreground ', ' #58B6DA ' ); NODE.P ();d Atamodel.add (node), var graphview = new Ht.graph.GraphView (Datamodel); Graphview.addtodom (); Graphview.layout ({x:0, y:80, width:170, height:30});

We created a node, set the Image property of node to our defined vector, and then created a Graphview component that displays node in the Graphview network topology diagram .

Then let's simulate the file upload progress and let the progress bar move up.

function Setprogressvalue (node) {    var value = Node.getvalue ();    if (value!==) {        Node.setvalue (value + 1);        var second = Math.Round (Math.random () *);        SetTimeout (Setprogressvalue, Second, node);}    }

We continually set the value of node by using the SetTimeout () method. However, the code executes and you will find out. The progress bar is not moving at all. Consistent in the initial state, when we zoom Graphview, we can see the progress bar is changing, this is why? In fact the reason is very easy. We did not notify Graphview to update the value when we changed it, so the progress bar does not change because of the value change of node, so how do we notify the Graphview update? method is very easy, after changing the value of node, the dispatch of a PropertyChange event can be, after the creation of the node code to add such as the following code:

Node.getvalue = function () {    return this._value;}; Node.setvalue = function (value) {    var self = this,        OV = Self._value;    Self._value = value;    SELF.FP (' value ', OV, value);};

The code. The PropertyChange event is distributed through the FP () method, so that the progress bar works correctly and changes as node's value changes, such as the following:


But another point, although the progress bar is running, but we still do not know the current progress is how much, only through the proportion of the progress bar to approximate the current progress value, we can add a text on the progress bar to display the current progress value. The answer is yes, we just need to add the following code to the comps of the vector, for example:

Draw text {    rect: {x:118, y:0, width:32, height:12},    type: ' Text ',    text: {func:function (data) {Retur n data.getvalue () + '% ';},    font: ' 12px Arial, Sans-ferif ',    color: ' Black '}

The same binding applies to the code, binding the current value of node, for example, the following:


Now the progress bar and finally effect on the round angle, then how to achieve the round angle? In fact, it is not difficult, just draw a rounded rectangle and combine the clip () method to intercept portions of the rectangular area beyond the rounded corners. A specific introduction to the clip () method can be introduced in the MDN .

1. First. We need to create a method of swinging a rounded rectangle:

/*** * Draw round Edge Rectangle * @param CTX BRUSH * @param x Coordinate x * @param y coordinate y * @param width Width * @param height height * @param radius Corner Radius * * function RoundRect (CTX, x, y, Width, height, radius) {    ctx.beginpath ();    Ctx.moveto (x, y + radius);    Ctx.lineto (x, y + height-radius);    Ctx.quadraticcurveto (x, y + height, x + radius, y + height);    Ctx.lineto (x + width-radius, y + height);    Ctx.quadraticcurveto (x + width, y + height, x + width, y + height-radius);    Ctx.lineto (x + width, y + radius);    Ctx.quadraticcurveto (x + width, y, x + Width-radius, y);    Ctx.lineto (x + radius, y);    Ctx.quadraticcurveto (x, y, x, y + radius);}

2. Call the RoundRect () method using the method of your own definition type. Draw a rounded rectangular area and then call the clip () method to truncate the outer part of the rounded rectangular area.

It is important to note that the clip () method intercepts only the content that is drawn after the method is called, and the content that is drawn before the method is called is not truncated.

So the following code must be placed before the code that paints the background.

Draw Rounded Rectangle {    rect: {x:0, y:0, width:115, height:12},    type:function (g, Rect, comp, data, view) {        var w Idth = rect.width, height = rect.height;        RoundRect (g, 0, 0, width, height, height/2);        G.clip ();    }}

Look how it works.


At this point, the design of the progress bar is over. Then let's look at how the progress bar is combined with file uploads:

1. First of all, we need to have a server to receive files, in addition to the use of regular webserver server (webserver simple configuration can refer to:HT for Web HTML5 Tree Component delay loading technology implementation ), also used the Formidable module . The following is the code for the server:

var express = require (' Express '), App = Express (), Server = require (' http '). Createserver (APP), Io = require (' Sock Et.io ') (server), Path = require (' path '), root = Path.join (__dirname, '. /.. /.. /'), formidable = require (' formidable ');//IO Monitor Connection Event Io.on (' Connection ', function (socket) {//define socket name so Cket.join (' upload ');}); /Set the server's working path App.use (express.static (root)); App.post ('/', function (req, res) {var form = new Formidable.    Incomingform ();    Form.on (' End ', function () {res.end (' upload complete! ');    }); Form.on (' Progress ', function (bytesreceived, bytesexpected) {var percent = Math.floor (bytesreceived/bytesexpected        * 100); Gets the specified socket.    and dispatch event io.sockets.in (' upload '). Emit (' progress ', percent);    }); Form.parse (req);}); /server Monitoring 4000 Port Server.listen ((), function () {Console.log (' server is listening at Port 3000 ');});

2. Second. We need to design a document upload form:

<form method= "POST" action= "/" enctype= "Multipart/form-data" name= "Fileform" >    <p><input type= " File "name=" file "/></p>    <p><input type=" Submit "value=" Upload "/></p></form>

3. Furthermore, we need to upload files to the server in conjunction with Ajax without flushing. And with the socket technology to monitor the server event, how to use the socket in the browser can refer to:HT for Web HTML5 Tree Component delay loading technology implementation .

var fileform = Document.forms.namedItem (' Fileform '); Fileform.addeventlistener (' Submit ', function (e) {    var HttpRequest;    if (window. XMLHttpRequest) {//Mozilla, Safari, ie7+        ... HttpRequest = new XMLHttpRequest ();    }    else if (window. ActiveXObject) {//IE 6 and older        HttpRequest = new ActiveXObject ("Microsoft.XMLHTTP");    }    Httprequest.open (' POST ', '/', true);    Httprequest.send (New FormData (Fileform));    Socket.on (' Progress ', function (val) {        progress.setvalue (val);    });    E.preventdefault ();}, False);

Thus, based on the HT for Web own definition class implementation HTML5 File upload progress bar page design and code design all finished, because of the length of the relationship. In the fromidable aspect is less, also hope forgive me, the following I say attached complete code, interested students can download down research.

Click to download source code


Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

Implement HTML5 File upload progress bar based on HT for web vector

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.