web file upload and renewal of BeetleX

Keywords: Programming network html5 JQuery Vue

It is a common function to upload files in web applications, but it is more troublesome to upload large files in the traditional way. After all, once the network is abnormal, it is easy to cause file upload failure and need to start again. This article introduces the web file upload function of BeetleX. Its feature is that it supports disconnection and continuous transmission. When the network recovers abnormally, the components can continue the transmission of subsequent content. This function does not need to install any plug-ins separately, as long as the browser supports HTML5, it can support this function. Next, an example is given to show how to implement a web file upload function that supports multi file, offline continuous transmission and drag and drop.

Function interface

First let's take a look at the full functionality of this example

The above functions include file selection and drag and drop file upload, and support automatic resume upload without closing browser after disconnection

Realization

Due to the encapsulation of beetlex, it only needs a few lines of code to complete the above functions, which can be said to be simpler than the traditional jquery upload.

<body>
    <div id="page">
        <page-header>

        </page-header>
        <div class="container" style="margin-top:60px;">
            <div class="row">
                <form>
                    <div class="form-group">                     
                        <input ref="upload" @change="onUpload" type="file" multiple>
                    </div>                
                </form>
                <div @drop="onFileDrop" @dragover="event.preventDefault();" class="panel panel-default" style="min-height:400px;">
                    <div v-for="item in uploadFiles.items" class="upload-bar">
                        <div class="uploadstats-bar" :style="{width:item.percent+'%'}">[{{item.percent}}%]{{item.name}}</div>
                    </div>
                </div>
            </div>
        </div>

    </div>
    <script>
        beetlex.useWebsocket();
        var model = {
            uploadFiles: new UploadFiles('/Upload'),
        };
        var page = new Vue({
            el: '#page',
            data: model,
            methods: {
                onUpload: function () {
                    var files = this.$refs.upload.files;
                    if (files.length == 0)
                        return;
                    this.uploadFiles.addmulti(files);
                    this.$refs.upload.value = null;
                },
                onFileDrop: function (event) {
                    event.preventDefault();
                    this.uploadFiles.addmulti(event.dataTransfer.files);
                }
            }
        });
        beetlex.websocket.connected = function () {
            //Sequel
            page.uploadFiles.upload();
        };
    </script>
</body>

beetlex

It is a communication class encapsulated specifically for http and websocket. Because this upload function uses websocket by default, it needs to enable the support of components for websocket. The opening code is as follows:

 beetlex.useWebsocket()

UploadFiles

This is the encapsulation class of the uploaded file, through which the file is uploaded; the parameter is to specify the Url of the submitted content, and finally add the files to be uploaded through the addmulti and add methods; the added files will be uploaded to the corresponding service interface one by one in order.

Sequel

Because it is transmitted through websocket when transferring large files, the upload may be incomplete due to the disconnection of the connection, which needs to continue after the component automatically creates the connection. The specific code is as follows:

beetlex.websocket.connected = function () {
            //Sequel
     page.uploadFiles.upload();
};

beetlex will automatically detect the connection status. When the connection is disconnected, it will automatically attempt to reconnect, and resume the upload by binding the connection event

Server code

    class Program
    {
        static void Main(string[] args)
        {
            var builder = new HostBuilder()
                .ConfigureServices((hostContext, services) =>
                {
                    services.UseBeetlexHttp(o =>
                    {
                        o.LogToConsole = true;
                        o.ManageApiEnabled = false;
                        o.WebSocketMaxRPS = 0;
                        o.Port = 80;
                        o.SetDebug();
                        o.LogLevel = BeetleX.EventArgs.LogType.Warring;
                    },
                    typeof(Program).Assembly);
                });
            builder.Build().Run();
        }
    }

    [BeetleX.FastHttpApi.Controller]
    public class Home
    {
        public void Upload(string name, string data, bool completed, int index, int buffersize, long filesize)
        {
            byte[] buffer = System.Convert.FromBase64String(data);
            using (System.IO.Stream stream =
                index == 0 ? System.IO.File.Create(name) : System.IO.File.Open(name, System.IO.FileMode.OpenOrCreate))
            {
                if (stream.Length > buffersize * index)
                    stream.Position = buffersize * index;
                else
                    stream.Seek(0, System.IO.SeekOrigin.End);
                stream.Write(buffer, 0, buffer.Length);
                stream.Flush();
            }
        }
    }

Online demo

http://upload.ikende.com/

Sample code

https://github.com/IKende/BeetleX-Samples/tree/master/WebSocket.UploadFiles

Posted by webgod on Sun, 22 Dec 2019 04:51:07 -0800