.NetCore + WebUploader achieve large file uploads slices

Project requirements upload large files through the site, such as video files, to achieve a fumble by file fragmentation to upload, and then merge the background.

Uses the open source front desk upload the plugin WebUploader (http://fex.baidu.com/webuploader/)

WebUploader by Baidu WebFE (FEX) team developed a simple to HTML5-based, FLASH, supplemented by modern file upload component. In modern browsers which can give full play to the advantages of HTML5, while not abandon mainstream IE browser, follow the original FLASH operation, compatible with IE6 +, iOS 6+, android 4+. Two run-time, the same way calls for the user to arbitrarily choose.

Using a large slice of concurrent file upload, file upload greatly improves efficiency.

 

Directly on the code, the front desk cshtml

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <link href="~/js/webuploader/webuploader.css" rel="stylesheet" />
    <link href="~/js/bootstrap.min.css" rel="stylesheet" />
    <script src="~/js/jquery.min.js"></script>
    <script src="~/js/webuploader/webuploader.js"></script>
    <title>Upload</title>
    <script>
        jQuery(function () {
            var $ = jQuery,
                $list = $('#thelist'),
                $btn = $('#ctlBtn'),
                state = 'pending',
                fileMd5,
                = to true In Flag, 
                "before-send": "beforeSend",
                dataState, 
                FM = [], 
                FNUM, 
                the Token, 
                Uploader; 
            var FileExt = [ "MPG", "MPEG", "MP4", "AVI"]; 
            the Token = '@ ViewBag.Token'; 
            IF (the Token == '' the Token == || 'undefined') 
            { 
                $ ( "# Uploader") hide ();. 
                Alert ( "login timeout, log in again."); 
            } 
            three time points // monitor block upload process 
            WebUploader .Uploader.register ({ 
                "Send-before-File": "beforeSendFile", 
                "After-Send-File": "afterSendFile",
            }, {
                    beforeSendFile: function (file) {
                        var startTime = new Date(file.lastModifiedDate);
                        fileName = file.name;
                        var deferred = WebUploader.Deferred(); 
                        (new WebUploader.Uploader()).md5File(file, 0, 10 * 1024 * 1024)
                            .progress(function (percentage) {
                                console.log("正在读取文件");
                            })
                            .then(function (val) {
                                fileMd5 = val;
                                fm.push(fileMd5); 
                                deferred.resolve();
                            }); 
                        Return deferred.promise (); 
                    }, 
                    afterSendFile: function (file) {
                    // time point 2: If watched upload blocks, each block call this function before uploading 
                    beforeSend: function (Block) { 
                        var deferreds WebUploader.Deferred = (); 
 
                        Ajax block is detected at the front // This file has been uploaded Upload 
 
                        this.owner.options.formData.fileMd5 = fileMd5; 
                        this.owner.options.formData.chunk = block.chunk; 
                        deferred.resolve (); 
                        return deferred.promise (); 
                    }, 
                    // 3 time points: all points after calling this function block is successfully uploaded 
                        var deferreds .Deferred = $ (); 
                        $ ( '#' + file.id) .find ( 'p.state') text ( 'last step');. 
                        the console.log (File );
                        console.log(file.guid);
                        $.ajax({
                            type: "POST",
                            url: "/api/v1/Check/FileMerge",
                            data: {
                                guid: file.guid,
                                fileMd5: fm[fnum],
                                fileName: file.name
                            },
                            cache: false,
                            async: false,
                            success: function (response) {
                                fnum++;
                                console.log(response);
                                if (response.success == true) {
                                    dataState = response;
                                    flag = true;
                                } else {
                                    flag = false;
                                }
                                deferred.resolve();
                            },
                            error: function () {
                                fnum++;
                                dataState = undefined;
                                flag = false;
                                deferred.reject();
                            }
                        });
 
                        return deferred.promise();
                    }
                });
            uploader = WebUploader.create({
                resize: false,
                fileNumLimit: 10,
                swf: '/js/Uploader.swf',
                server: '/api/v1/Check/FileSave',
                pick: '#picker',
                chunked: true,
                chunkSize: 10 * 1024 * 1024,
                chunkRetry: 5
                //, formData: {
                //    guid: GUID
                //}
            });
            uploader.on('beforeFileQueued', function (file) {
                var isAdd = false;
                for (var i = 0; i < FileExt.length; i++) {
                    if (file.ext == FileExt[i]) {
                        file.guid = WebUploader.Base.guid();
                        isAdd = true;
                        break;
                    }
                }
                return isAdd;
            });
            uploader.on('uploadBeforeSend', function (object, data, headers) {
                //console.log(object);
                headers.Authorization =Token;
                data.guid = object.file.guid;
            });
            // 当有文件添加进来的时候
            uploader.on('fileQueued', function (file) {
                list.append $ ( '<div ID = "' + file.id + '" class = "Item">' + 
                    '<h4 class="info">' + file.name + '</h4>' +
                    '<INPUT type = "hidden" ID = "H_' file.id + + '" value = " '+ file.guid +' "/> '+ 
                    ' <P class =" State "> waiting for upload ... </ P> '+ 
                    ' </ div> '); 
            }); 
 
            // Create the file upload process The progress bar is displayed in real time. 
            uploader.on ( 'uploadProgress', function (File, PERCENTAGE) { 
                var $ Li = $ ( '#' + file.id), 
                    $ $ li.find Percent = () 'Progress. Progress-bar.'; 
                // avoid duplication created 
                if (! $ percent. 
                        ' < class = div "ProgressBar" Role = "ProgressBar" style = "width: 0%"> '+ 
                        ' </ div> '
 
                $percent.css('width', percentage * 100 + '%');
            });
 
            uploader.on('uploadSuccess', function (file) {
                if (dataState == undefined) {
                    $('#' + file.id).find('p.state').text('上传失败');
                    $('#' + file.id).find('button').remove();
                    $('#' + file.id).find('p.state').before('<button id="retry" type="button" class="btn btn-primary fright retry pbtn">重新上传</button>');
                    = to false In Flag; 
                    file.setStatus ( 'error'); 
                } 
                IF (== dataState.success to true) { 
                    . $ ( '#' + file.id) .find ( 'p.state') text ( 'uploaded' ); 
                    $ ( '#' + file.id) .find ( 'Button') Remove ();. 
 
                } else {
                    . $ ( '#' + file.id) .find ( 'p.state') text ( "failed to upload ' ); 
                    In Flag = to false; 
                } 
            }); 
 
            uploader.on ( 'the uploadError', function (File) { 
                . $ ( '#' + file.id) .find ( 'p.state') text ( 'Upload error') ; 
            }); 
 
            uploader.on ( 'uploadComplete',function (file) {
                $ ( '#' + File.id) .find ( 'Progress.'). FadeOut ();. 
            }); 
 
            Uploader.on ( 'All', function (type) { 
                IF (type === 'the startUpload') { 
                    = State 'uploading'; 
                } the else IF (type === 'stopUpload') { 
                    state = 'paused';
                } else if (type === 'uploadFinished') {
                    State = 'DONE'; 
                } 
                IF (State === 'DONE') { 
                    $ btn.text ( 'continue to upload'); 
                } the else IF (State === 'uploading') { 
                    $ btn.text ( 'pause upload'); 
                } the else { 
                    $ btn.text ( 'start upload');
                }
            });
            $btn.on('click', function () { 
                IF (State ===' uploading ') { 
                    uploader.stop (); 
                } the else IF (State ==' DONE ') { 
                    window.location.reload (); 
                } 
                the else { 
                    uploader.upload ();
                }
            });
        });
    </script>
</head>
<body>
    <div id="uploader" class="wu-example">
        <span style="color:red">只能上传mpg、mpeg、mp4、avi格式的视频文件</span>
        <div id="thelist" class="uploader-list"></div>
        <div class="btns">
            <div id="picker" class="webuploader-container"><div class="webuploader-pick">选择文件</div><div style="position: absolute; top: 0px; left: 0px; width: 88px; height: 34px; overflow: hidden; bottom: auto; right: auto;"><input type="file" name="file" class="webuploader-element-invisible" multiple="multiple"><label style="opacity: 0; width: 100%; height: 100%; display: block; cursor: pointer; background: rgb(255, 255, 255);"></label></div></div>
            <button id="ctlBtn" class="btn btn-default">开始上传</button> 
        </div>
    </div>
</body>
</html>

Background Code:

#region uploaded videos 
        public IActionResult the Upload () 
        { 
            ; // get the authentication information when provided, is transmitted to the front desk, Ajax = HttpContext.Request.Headers request ViewBag.Token [ "the Authorization"] 
            return View (); 
        } 
        /// < Summary> 
        /// uploaded 
        /// </ Summary> 
        /// <Returns> </ Returns> 
        [HttpPost] 
        public the async the Task <IActionResult> the FileSave () 
        { 
            var = DATE the Request; 
            var = Request.Form.Files files ; 
            Long files.Sum size = (F => f.Length); 
            the foreach (var FormFile in Files) 
            { 
                IF (formFile.Length>0)
                { 
                    String FileExt = formFile.FileName.Substring (formFile.FileName.IndexOf () '.'); "." // file extension, free 
                    long fileSize = formFile.Length; // get file size in bytes units 
                    . "." // string newFileName = Guid.NewGuid () ToString () + + fileExt; // randomly generates a new file name 
                    string DirPath = Path.Combine (_uploadConfig.TmpPath, Request.Form [ "guid"]) ; 
                    IF (Directory.Exists (DirPath)!) 
                    { 
                        Directory.CreateDirectory (DirPath); 
                    } 
                    var filePath = DirPath + "/" + the Request.Form [ "the chunk"] + FileExt;
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);
 
                    }
                }
            }
            return Ok(new { count = files.Count, size });
        }
 
        /// <summary>
        /// 合并请求
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> FileMerge()
        {
            bool ok = false;
            string errmsg = "";
            try
            {
                var temporary = Path.Combine(_uploadConfig.TmpPath, Request.Form["guid"]);//临时文件夹
                string fileName = Request.Form [ "fileName" ]; // filename 
                string fileExt = Path.GetExtension (fileName); // get the file suffix 
                var files = Directory.GetFiles (temporary); // get all of the following documents 
              
                var finalFilePath = Path.Combine (_uploadConfig.UpLoadPath + fileName); // end file name 
                // var new new FS = the FileStream (finalFilePath, FileMode.Create); 
                the using (var new new FS = the FileStream (finalFilePath, FileMode.Create)) 
                { 
                    the foreach (var files.OrderBy in Part (X => x.length) .ThenBy (X => X)) 
                    {  
                        var bytes = System.IO.File.ReadAllBytes (Part);
                        the await fs.WriteAsync (bytes, 0, bytes.Length); 
                        bytes = null;
                        System.IO.File.Delete(part);//删除分块
                    }
                    Directory.Delete(temporary);//删除文件夹
                    ok = true;
                }
            }
            catch (Exception ex)
            {
                ok = false;
                errmsg = ex.Message;
                log4net.Error(errmsg);
            }
            if (ok)
            {
                return Ok(new { success = true, msg = "" });
            }
            else
            {
                return Ok(new { success = false, msg = errmsg }); ;
            }
        }
 
        #endregion

 

Guess you like

Origin www.cnblogs.com/wdw984/p/11725118.html