天天看點

用HTML5實作分片上傳GB級大檔案思路

需求:項目要支援大檔案上傳功能,經過讨論,初步将檔案上傳大小控制在500M内,是以自己需要在項目中進行檔案上傳部分的調整和配置,自己将大小都以501M來進行限制。

第一步:

前端修改

由于項目使用的是BJUI前端架構,并沒有使用架構本身的檔案上傳控件,而使用的基于jQuery的Uploadify檔案上傳元件,在項目使用的jslib項目中找到了BJUI架構內建jQuery Uploadify的部分,這部分代碼封裝在bjui-all.js檔案中,

在bjui-all.js檔案中的全局變量定義中有以下部分代碼,這就是定義的有關于上傳的Uploadify控件的重要變量:

//檔案上傳對象

function FileUploader(fileLoc, mgr)

{

    var _this = this;

    this.id = fileLoc.id;

    this.ui = { msg: null, process: null, percent: null, btn: { del: null, cancel: null,post:null,stop:null }, div: null};

    this.isFolder = false; //不是檔案夾

    this.app = mgr.app;

    this.Manager = mgr; //上傳管理器指針

    this.event = mgr.event;

    this.Config = mgr.Config;

    this.fields = jQuery.extend({}, mgr.Config.Fields, fileLoc.fields);//每一個對象自帶一個fields幅本

    this.State = this.Config.state.None;

    this.uid = this.fields.uid;

    this.fileSvr = {

          pid: ""

        , id: ""

        , pidRoot: ""

        , f_fdTask: false

        , f_fdChild: false

        , uid: 0

        , nameLoc: ""

        , nameSvr: ""

        , pathLoc: ""

        , pathSvr: ""

        , pathRel: ""

        , md5: ""

        , lenLoc: "0"

        , sizeLoc: ""

        , FilePos: "0"

        , lenSvr: "0"

        , perSvr: "0%"

        , complete: false

        , deleted: false

    };//json obj,伺服器檔案資訊

    this.fileSvr = jQuery.extend(this.fileSvr, fileLoc);

    //準備

    this.Ready = function ()

    {

        this.ui.msg.text("正在上傳隊列中等待...");

        this.State = this.Config.state.Ready;

        this.ui.btn.post.click(function () {

            _this.ui.btn.post.hide();

            _this.ui.btn.del.hide();

            _this.ui.btn.cancel.hide();

            _this.ui.btn.stop.show();

            if (!_this.Manager.IsPostQueueFull()) {

                _this.post();

            }

            else {

                _this.ui.msg.text("正在上傳隊列中等待...");

                _this.State = _this.Config.state.Ready;

                $.each(_this.ui.btn, function (i, n) { n.hide(); });

                _this.ui.btn.del.show();

                //添加到隊列

                _this.Manager.AppendQueue(_this.fileSvr.id);

            }

        });

        this.ui.btn.stop.click(function () {

            _this.stop();

        });

        this.ui.btn.del.click(function () {

            _this.stop();

            _this.remove();

        });

        this.ui.btn.cancel.click(function () {

            _this.stop();

            _this.remove();

            //_this.PostFirst();//

        });

    };

    this.svr_error = function ()

    {

        alert("伺服器傳回資訊為空,請檢查伺服器配置");

        this.ui.msg.text("向伺服器發送MD5資訊錯誤");

        //this.ui.btn.cancel.text("續傳");

        this.ui.btn.stop.hide();

        this.ui.btn.cancel.show();

    };

    this.svr_error_same_name = function () {       

        this.ui.msg.text("伺服器存在同名檔案");

        this.ui.btn.stop.hide();

        this.ui.btn.cancel.show();

    };

    this.svr_create = function (sv)

    {

        if (sv.value == null)

        {

            this.Manager.RemoveQueuePost(this.fileSvr.id);

            this.svr_error(); return;

        }

        if (!sv.ret) {

            this.Manager.RemoveQueuePost(this.fileSvr.id);

            this.svr_error_same_name(); return;

        }

        var str = decodeURIComponent(sv.value);//

        this.fileSvr = JSON.parse(str);//

        //伺服器已存在相同檔案,且已上傳完成

        if (this.fileSvr.complete)

        {

            this.post_complete_quick();

        } //伺服器檔案沒有上傳完成

        else

        {

            this.ui.process.css("width", this.fileSvr.perSvr);

            this.ui.percent.text(this.fileSvr.perSvr);

            this.post_file();

        }

    };

    this.svr_update = function () {

        if (this.fileSvr.lenSvr == 0) return;

        var param = { uid: this.fields["uid"], offset: this.fileSvr.lenSvr, lenSvr: this.fileSvr.lenSvr, perSvr: this.fileSvr.perSvr, id: this.id, time: new Date().getTime() };

        $.ajax({

            type: "GET"

            , dataType: 'jsonp'

            , jsonp: "callback" //自定義的jsonp回調函數名稱,預設為jQuery自動生成的随機函數名

            , url: this.Config["UrlProcess"]

            , data: param

            , success: function (msg) {}

            , error: function (req, txt, err) { alert("更新檔案進度錯誤!" + req.responseText); }

            , complete: function (req, sta) { req = null; }

        });

    };

    this.svr_remove = function ()

    {

        var param = { uid: this.fields["uid"], id: this.fileSvr.id, time: new Date().getTime() };

        $.ajax({

            type: "GET"

            , dataType: 'jsonp'

            , jsonp: "callback" //自定義的jsonp回調函數名稱,預設為jQuery自動生成的随機函數名

            , url: this.Config["UrlDel"]

            , data: param

            , success: function (msg) { }

            , error: function (req, txt, err) { alert("删除檔案失敗!" + req.responseText); }

            , complete: function (req, sta) { req = null; }

        });

    };

    this.post_process = function (json)

    {

        this.fileSvr.lenSvr = json.lenSvr;//儲存上傳進度

        this.fileSvr.perSvr = json.percent;

        this.ui.percent.text("("+json.percent+")");

        this.ui.process.css("width", json.percent);

        var str = json.lenPost + " " + json.speed + " " + json.time;

        this.ui.msg.text(str);

    };

    this.post_complete = function (json)

    {

        this.fileSvr.perSvr = "100%";

        this.fileSvr.complete = true;

        $.each(this.ui.btn, function (i, n)

        {

            n.hide();

        });

        this.ui.process.css("width", "100%");

        this.ui.percent.text("(100%)");

        this.ui.msg.text("上傳完成");

        this.Manager.arrFilesComplete.push(this);

        this.State = this.Config.state.Complete;

        //從上傳清單中删除

        this.Manager.RemoveQueuePost(this.fileSvr.id);

        //從未上傳清單中删除

        this.Manager.RemoveQueueWait(this.fileSvr.id);

        var param = { md5: this.fileSvr.md5, uid: this.uid, id: this.fileSvr.id, time: new Date().getTime() };

        $.ajax({

            type: "GET"

              , dataType: 'jsonp'

              , jsonp: "callback" //自定義的jsonp回調函數名稱,預設為jQuery自動生成的随機函數名

              , url: _this.Config["UrlComplete"]

              , data: param

              , success: function (msg)

              {

                  _this.event.fileComplete(_this);//觸發事件

                  _this.post_next();

              }

              , error: function (req, txt, err) { alert("檔案-向伺服器發送Complete資訊錯誤!" + req.responseText); }

              , complete: function (req, sta) { req = null; }

        });

    };

    this.post_complete_quick = function ()

    {

        this.fileSvr.perSvr = "100%";

        this.fileSvr.complete = true;

        this.ui.btn.stop.hide();

        this.ui.process.css("width", "100%");

        this.ui.percent.text("(100%)");

        this.ui.msg.text("伺服器存在相同檔案,快速上傳成功。");

        this.Manager.arrFilesComplete.push(this);

        this.State = this.Config.state.Complete;

        //從上傳清單中删除

        this.Manager.RemoveQueuePost(this.fileSvr.id);

        //從未上傳清單中删除

        this.Manager.RemoveQueueWait(this.fileSvr.id);

        //添加到檔案清單

        this.post_next();

        this.event.fileComplete(this);//觸發事件

    };

    this.post_stoped = function (json)

    {

        this.ui.btn.post.show();

        this.ui.btn.del.show();

        this.ui.btn.cancel.hide();

        this.ui.btn.stop.hide();

        this.ui.msg.text("傳輸已停止....");

        if (this.Config.state.Ready == this.State)

        {

            this.Manager.RemoveQueue(this.fileSvr.id);

            this.post_next();

            return;

        }

        this.State = this.Config.state.Stop;

        //從上傳清單中删除

        this.Manager.RemoveQueuePost(this.fileSvr.id);

        this.Manager.AppendQueueWait(this.fileSvr.id);//添加到未上傳清單

        //傳輸下一個

        this.post_next();

    };

    this.post_error = function (json)

    {

        this.svr_update();

        this.ui.msg.text(this.Config.errCode[json.value]);

        this.ui.btn.stop.hide();

        this.ui.btn.post.show();

        this.ui.btn.del.show();

        this.State = this.Config.state.Error;

        //從上傳清單中删除

        this.Manager.RemoveQueuePost(this.fileSvr.id);

        //添加到未上傳清單

        this.Manager.AppendQueueWait(this.fileSvr.id);

        this.post_next();

    };

    this.md5_process = function (json)

    {

        var msg = "正在掃描本地檔案,已完成:" + json.percent;

        this.ui.msg.text(msg);

    };

    this.md5_complete = function (json)

    {

        this.fileSvr.md5 = json.md5;

        this.ui.msg.text("MD5計算完畢,開始連接配接伺服器...");

        this.event.md5Complete(this, json.md5);//biz event

        var loc_path = encodeURIComponent(this.fileSvr.pathLoc);

        var loc_len = this.fileSvr.lenLoc;

        var loc_size = this.fileSvr.sizeLoc;

        var param = jQuery.extend({}, this.fields, this.Config.bizData, { md5: json.md5, id: this.fileSvr.id, lenLoc: loc_len, sizeLoc: loc_size, pathLoc: loc_path, time: new Date().getTime() });

        $.ajax({

            type: "GET"

            , dataType: 'jsonp'

            , jsonp: "callback" //自定義的jsonp回調函數名稱,預設為jQuery自動生成的随機函數名

            , url: this.Config["UrlCreate"]

            , data: param

            , success: function (sv)

            {

                _this.svr_create(sv);

            }

            , error: function (req, txt, err)

            {

                _this.Manager.RemoveQueuePost(_this.fileSvr.id);

                alert("向伺服器發送MD5資訊錯誤!" + req.responseText);

                _this.ui.msg.text("向伺服器發送MD5資訊錯誤");

                _this.ui.btn.cancel.show();

                _this.ui.btn.stop.hide();

            }

            , complete: function (req, sta) { req = null; }

        });

    };

    this.md5_error = function (json)

    {

        this.ui.msg.text(this.Config.errCode[json.value]);

        //檔案大小超過限制,檔案大小為0

        if ("4" == json.value

              || "5" == json.value)

        {

        this.ui.btn.stop.hide();

        this.ui.btn.cancel.show();

        }

        else

        {           

            this.ui.btn.post.show();

            this.ui.btn.stop.hide();

        }

        this.State = this.Config.state.Error;

        //從上傳清單中删除

        this.Manager.RemoveQueuePost(this.fileSvr.id);

        //添加到未上傳清單

        this.Manager.AppendQueueWait(this.fileSvr.id);

        this.post_next();

    };

    this.post_next = function ()

    {

        var obj = this;

        setTimeout(function () { obj.Manager.PostNext(); }, 300);

    };

    this.post = function ()

    {

        this.Manager.AppendQueuePost(this.fileSvr.id);

        this.Manager.RemoveQueueWait(this.fileSvr.id);

        if (this.fileSvr.md5.length > 0 || this.fileSvr.lenSvr > 0)

        {

            this.post_file();

        }

        else

        {

            this.check_file();

        }

    };

    this.post_file = function ()

    {

        $.each(this.ui.btn, function (i, n) { n.hide();});

        this.ui.btn.stop.show();

        this.State = this.Config.state.Posting;//

        this.app.postFile({ id: this.fileSvr.id, pathLoc: this.fileSvr.pathLoc, pathSvr:this.fileSvr.pathSvr,lenSvr: this.fileSvr.lenSvr, fields: this.fields });

    };

    this.check_file = function ()

    {

        //this.ui.btn.cancel.text("停止").show();

        this.ui.btn.stop.show();

        this.ui.btn.cancel.hide();

        this.State = this.Config.state.MD5Working;

        this.app.checkFile({ id: this.fileSvr.id, pathLoc: this.fileSvr.pathLoc });

    };

    this.stop = function ()

    {

        $.each(this.ui.btn, function (i, n) { n.hide();});

        this.svr_update();

        this.app.stopFile({ id: this.fileSvr.id });       

    };

    //手動停止,一般在StopAll中調用

    this.stop_manual = function ()

    {

        if (this.Config.state.Posting == this.State)

        {

            this.svr_update();

        this.ui.btn.post.show();

        this.ui.btn.stop.hide();

        this.ui.btn.cancel.hide();

            this.ui.msg.text("傳輸已停止....");

            this.app.stopFile({ id: this.fileSvr.id ,tip:false});

            this.State = this.Config.state.Stop;

        }

    };

    //删除,一般在使用者點選"删除"按鈕時調用

    this.remove = function ()

    {

        this.Manager.del_file(this.fileSvr.id);

        this.app.delFile(this.fileSvr);

        this.ui.div.remove();

        if (this.State != this.Config.state.Complete) this.svr_remove();

    };

}

upload:{uploadLimit:5,fileSizeLimit:31744,removeTimeout:0.8}

以上三個變量代表的含義是:

uploadLimit:表示上傳檔案個數的限制,5表示檔案上傳個數限制是5個

fileSizeLimit:表示上傳檔案大小的限制,31744機關是KB,也就是表示31M

removeTimeout:表示移除檔案的時間限制

繼續查找使用到這些變量的地方,看到了檔案大小超出限制等

了解了BJUI前端架構對于上傳大檔案的限制,可以這樣使用,增大檔案上傳大小和數量,可以按照如下進行修改,我們在bjui-all.js檔案看到uploadLimit屬性和fileSizeLimit屬性的限制,我們在jsp檔案中可以這樣進行替換,這裡使用的是覆寫原則,重新定義uploadLimit屬性和fileSizeLimit屬性,覆寫bjui-all.js檔案的預設值設定。

bjui-all.js檔案的uploadLimit屬性和fileSizeLimit屬性對應到jsp檔案中的屬性就應該這樣寫,data-upload-limit屬性和data-file-size-limit屬性,隻需要在後面改寫為data-upload-limit=“800”和data-file-size-limit=“5131264”即可,一定要注意這裡的機關是KB,以上數字表示501M。

關于Uploadify控件屬性可以參考這篇文章也可以直接看官網文檔:

http://blog.ncmem.com/wordpress/2019/08/07/java超大檔案上傳與下載下傳/

屬性名稱 預設值 說明
auto true 設定為true當選擇檔案後就直接上傳了,為false需要點選上傳按鈕才上傳 。
buttonClass 按鈕樣式
buttonCursor ‘hand’ 滑鼠指針懸停在按鈕上的樣子
buttonImage null 浏覽按鈕的圖檔的路徑 。
buttonText ‘SELECT FILES’ 浏覽按鈕的文本。
checkExisting false 檔案上傳重複性檢查程式,檢查即将上傳的檔案在伺服器端是否已存在,存在傳回1,不存在傳回0
debug false 如果設定為true則表示啟用SWFUpload的調試模式
fileObjName ‘Filedata’ 檔案上傳對象的名稱,如果命名為’the_files’,PHP程式可以用$_FILES['the_files']來處理上傳的檔案對象。
fileSizeLimit

上傳檔案的大小限制 ,如果為整數型則表示以KB為機關的大小,如果是字元串,則可以使用(B, KB, MB, or GB)為機關,比如’2MB’;

如果設定為0則表示無限制

fileTypeDesc ‘All Files’ 這個屬性值必須設定fileTypeExts屬性後才有效,用來設定選擇檔案對話框中的提示文本,如設定fileTypeDesc為“請選擇rar doc pdf檔案”
fileTypeExts ‘*.*’ 設定可以選擇的檔案的類型,格式如:’*.doc;*.pdf;*.rar’   。
formData JSON格式上傳每個檔案的同時送出到伺服器的額外資料,可在’onUploadStart’事件中使用’settings’方法動态設定。
height 30 設定浏覽按鈕的高度 ,預設值
itemTemplate false

用于設定上傳隊列的HTML模版,可以使用以下标簽:

    instanceID –   Uploadify執行個體的ID

    fileID – 列隊中此檔案的ID,或者了解為此任務的ID

    fileName – 檔案的名稱

    fileSize – 目前上傳檔案的大小

    插入模版标簽時使用格式如:${fileName}

method Post 送出方式Post或Get
multi true 設定為true時可以上傳多個檔案。
overrideEvents 設定哪些事件可以被重寫,JSON格式,如:’overrideEvents’ : ['onUploadProgress']
preventCaching true 如果為true,則每次上傳檔案時自動加上一串随機字元串參數,防止URL緩存影響上傳結果
progressData ‘percentage’ 設定上傳進度顯示方式,percentage顯示上傳百分比,speed顯示上傳速度
queueID false 設定上傳隊列容器DOM元素的ID,如果為false則自動生成一個隊列容器。
queueSizeLimit 999

隊列最多顯示的任務數量,如果選擇的檔案數量超出此限制,将會出發onSelectError事件。

    注意此項并非最大檔案上傳數量,如果要限制最大上傳檔案數量,應設定uploadLimit。

removeCompleted true 是否自動将已完成任務從隊列中删除,如果設定為false則會一直保留此任務顯示。
removeTimeout 3 如果設定了任務完成後自動從隊列中移除,則可以規定從完成到被移除的時間間隔。
requeueErrors false 如果設定為true,則單個任務上傳失敗後将傳回錯誤,并重新加入任務隊列上傳。
successTimeout 30 檔案上傳成功後服務端應傳回成功标志,此項設定傳回結果的逾時時間
swf ‘uploadify.swf’ uploadify.swf 檔案的相對路徑。
uploader uploadify.php 背景處理程式的相對路徑。
uploadLimit 999 最大上傳檔案數量,如果達到或超出此限制将會觸發onUploadError事件。
width 120 設定檔案浏覽按鈕的寬度。

第二步:

後端修改

由于項目後端使用的Spring Boot,本身也就是使用的Spring MVC檔案上傳部分,Spring MVC使用的是已經對Servlet檔案上傳封裝了的MultipartResolver接口及其相關實作類和一些相關的類,具體的可以看Spring MVC檔案上傳源碼部分,認為Spring源碼還是需要讀的,我們隻要在Spring Boot啟動類中注入這個Bean,或者自行寫一個WebConfig配置類,注入一些Web相關的Bean即可,這樣Spring Boot啟動就會加載配置類,也需要自己寫攔截器和全局AOP切面,去捕捉檔案上傳大小超過限制的異常處理等

基于Spring MVC檔案上傳元件MultipartResolver接口(核心),使用其中的CommonsMultipartResolver(實作了MultipartResolver接口)這個實作類,CommonsMultipartResolver中的maxUploadSize屬性是它繼承的抽象父類CommonsFileUploadSupport,這個抽象類其中的一個屬性是FileUpload類,而這個類又繼承自FileUploadBase這個抽象類,其中它的private long sizeMax = -1;就是maxUploadSize屬性的最終設定地方。-1表示檔案上傳大小沒有限制,但是我們一般都會設定一個限制值,這裡設定的是210763776,這個值的機關是位元組,我們将它設定為525336576位元組,也就是501M的大小限制。

修改完以上前端和後端,送出修改的代碼到git上即可。

第三步:

Nginx配置

進入到項目部署釋出所在的Linux下,進入nginx伺服器所安裝的目錄,

進入到nginx伺服器所安裝的目錄

進入到nginx伺服器目錄下的conf目錄

檢視nginx.conf配置檔案内容中的client_max_body_size配置的大小,這裡設定的是300M。

使用vi或者vim打開nginx.conf配置檔案,修改client_max_body_size的大小為501M,儲存即可

進入到nginx伺服器下的sbin目錄下,我們使用./nginx -t檢視配置檔案是否成功使用,然後使用./nginx -s reload重新開機Nginx伺服器即可。

第四步:

Tomcat配置

由于項目使用的是Spring Cloud,自然使用Spring Boot,我們這個項目還是使用外置的Tomcat作為他的伺服器,便于我們對Tomcat伺服器進行優化和設定。

進入到項目使用的Tomcat伺服器的目錄

進入到指定項目使用的Tomcat伺服器的目錄

進入到Tomcat伺服器下的conf配置目錄中

看到server.xml配置檔案後

先行檢視Tomcat伺服器的配置,其中兩個屬性對于這次是比較重要的一個是connectionTimeout這個連接配接逾時時間設定以及預設的maxPostSize屬性的設定

使用vi或者vim打開server.xml配置檔案,修改connectionTimeout的大小為2000000,這個屬性的機關是毫秒,換算之後大概是半個小時,我們配置預設的maxPostSize屬性的值,預設情況下它的值是2097152,它的機關是位元組,也就是2M的大小,修改完儲存即可

修改完伺服器之後,使用釋出工具重新從git上拉取最新的代碼和部署釋出,重新啟動腳本即可完成修改,再次嘗試大檔案上傳,功能基本實作。

以上需要注意的是maxPostSize屬性在各個Tomcat版本中的不同,可以參考我寫的這篇文章:http://blog.ncmem.com/wordpress/2019/08/07/java超大檔案上傳與下載下傳/

歡迎入群一起讨論:374992201

繼續閱讀