1. 程式人生 > 其它 >上傳視訊加進度條思路

上傳視訊加進度條思路

需求:專案要支援大檔案上傳功能,經過討論,初步將檔案上傳大小控制在500M內,因此自己需要在專案中進行檔案上傳部分的調整和配置,自己將大小都以501M來進行限制。

第一步:

前端修改

由於專案使用的是BJUI前端框架,並沒有使用框架本身的檔案上傳控制元件,而使用的基於jQuery的Uploadify檔案上傳元件,在專案使用的jslib專案中找到了BJUI框架整合jQuery Uploadify的部分,這部分程式碼封裝在bjui-all.js檔案中,

在bjui-all.js檔案中的全域性變數定義中有以下部分程式碼,這就是定義的有關於上傳的Uploadify控制元件的重要變數:

//檔案上傳物件

functionFileUploader(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;

}

varstr = 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;

varparam = { uid:this.fields["uid"], offset:this.fileSvr.lenSvr, lenSvr:this.fileSvr.lenSvr, perSvr:this.fileSvr.perSvr, id:this.id, time:newDate().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()

{

varparam = { uid:this.fields["uid"], id:this.fileSvr.id, time:newDate().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);

varstr = 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);

varparam = { md5:this.fileSvr.md5, uid:this.uid, id:this.fileSvr.id, time:newDate().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)

{

varmsg ="正在掃描本地檔案,已完成:"+ 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

varloc_path = encodeURIComponent(this.fileSvr.pathLoc);

varloc_len =this.fileSvr.lenLoc;

varloc_size =this.fileSvr.sizeLoc;

varparam = jQuery.extend({},this.fields,this.Config.bizData, { md5: json.md5, id:this.fileSvr.id, lenLoc: loc_len, sizeLoc: loc_size, pathLoc: loc_path, time:newDate().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()

{

varobj =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

0

上傳檔案的大小限制 ,如果為整數型則表示以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