1. 程式人生 > >angularJs上傳檔案-以及遇到的坑

angularJs上傳檔案-以及遇到的坑

angularJs上傳檔案使用的是angular-file-upload控制元件。

先介紹一下這個控制元件的一些屬性和一些方法;

FileUploader
屬性
url {String}: 上傳檔案的伺服器路徑
alias {String}:  包含檔案的名稱,預設是file
queue {Array}: 上傳佇列
progress {Number}: 上傳佇列的進度,只讀
headers {Object}: 上傳的標頭檔案資訊, 瀏覽器需支援HTML5
formData {Array}: 與檔案一起傳送的表單資料
filters {Array}: 在檔案加入上傳佇列之前應用過濾器.,如果過濾器返回true則檔案加入佇列中
autoUpload {Boolean}: 檔案加入佇列之後自動上傳,預設是false
method {String}: 請求方式,預設是POST,瀏覽器需支援HTML5
removeAfterUpload {Boolean}: 檔案上傳成功之後從佇列移除,預設是false
isHTML5 {Boolean}: 如果瀏覽器支援HTML5上傳則返回true,只讀
isUploading {Boolean}: 檔案正在上傳中返回true,只讀
queueLimit {Number} : 最大上傳檔案數量(預定義)
withCredentials {Boolean} : 使用CORS,預設是false, 瀏覽器需支援HTML5
方法
addToQueue function(files[, options[, filters]]) {: Add items to the queue, where files is a {FileList|File|HTMLInputElement}, options is an {Object} andfilters is a {String}.  新增項到上傳佇列中,files 是 {FileList|File|HTMLInputElement}, options 是 {Object} 以及 filters 是 {String}
removeFromQueue function(value) {: Remove an item from the queue, wherevalue is {FileItem} or index of item.  從上傳佇列移除項,value 可以是 {FileItem} 或者項的序號
clearQueue function() {: Removes all elements from the queue.  移除上傳佇列所有的元素
uploadItem function(value) {: Uploads an item, where value is {FileItem} or index of item.  上傳項, value 可以是 {FileItem} 或者項的序號
cancelItem function(value) {: Cancels uploading of item, where value is{FileItem} or index of item.  取消上傳的項
uploadAll function() {: Upload all pending items on the queue.  將上傳佇列中所有的項進行上傳
cancelAll function() {: Cancels all current uploads.  取消所有當前上傳
destroy function() {: Destroys a uploader. 
isFile function(value) {return {Boolean};}: Returns true if value is {File}. 
isFileLikeObject function(value) {return {Boolean};}: Returns true if value is{FileLikeObject}.
getIndexOfItem function({FileItem}) {return {Number};}: Returns the index of the{FileItem} queue element.  返回項在上傳佇列中的序號
getReadyItems function() {return {Array.<FileItems>};}: Return items are ready to upload.  返回準備上傳的項
getNotUploadedItems function() {return {Array.<FileItems>};}: Return an array of all pending items on the queue  返回上傳佇列中未上傳的項
回撥函式
onAfterAddingFile function(item) {: 新增檔案到上傳佇列後
onWhenAddingFileFailed function(item, filter, options) {: 新增檔案到上傳佇列失敗後
onAfterAddingAll function(addedItems) {: 新增所選的所有檔案到上傳佇列後
onBeforeUploadItem function(item) {: 檔案上傳之前
onProgressItem function(item, progress) {: 檔案上傳中
onSuccessItem function(item, response, status, headers) {: 檔案上傳成功後
onErrorItem function(item, response, status, headers) {: 檔案上傳失敗後
onCancelItem function(item, response, status, headers) { - 檔案上傳取消後
onCompleteItem function(item, response, status, headers) {: 檔案上傳完成後
onProgressAll function(progress) {: 上傳佇列的所有檔案上傳中
onCompleteAll function() {: 上傳佇列的所有檔案上傳完成後
成功上傳檔案的回撥函式順序是:onAfterAddingFile — onAfterAddingAll — onBeforeUploadItem — onProgressItem — onProgressAll — onSuccessItem — onCompleteItem — onCompleteAll
FileItem
屬性
url {String}: Path on the server in which this file will be uploaded  上傳檔案的伺服器路徑
alias {String}: Name of the field which will contain the file, default is file  包含檔案的名稱,預設是file
headers {Object}: Headers to be sent along with this file. HTML5 browsers only.  上傳的標頭檔案資訊, 瀏覽器需支援HTML5
formData {Array}: Data to be sent along with this file  與檔案一起傳送的表單資料
method {String}: It's a request method. By default POST. HTML5 browsers only.  請求方式,預設是POST,瀏覽器需支援HTML5
withCredentials {Boolean} : enable CORS. HTML5 browsers only.  使用CORS,預設是false, 瀏覽器需支援HTML5
removeAfterUpload {Boolean}: Remove this file from the queue after uploading  上傳之後從上傳佇列移除該檔案
index {Number} - A sequence number upload. Read only.  上傳檔案在上傳佇列中的序號,只讀
progress {Number}: File upload progress percentage. Read only.  檔案上傳的進度,只讀
isReady {Boolean} - File is ready to upload. Read only.  檔案是否準備好上傳,只讀
isUploading {Boolean}: true if the file is being uploaded. Read only.  檔案是否正在上傳中,只讀
isUploaded {Boolean}: true if the file was uploaded. Read only.  檔案是否已經上傳,只讀
isSuccess {Boolean}: true if the file was uploaded successfully. Read only.  檔案是否已經上傳成功,只讀
isCancel {Boolean} : true if uploading was canceled. Read only.  檔案是否取消上傳,只讀
isError {Boolean} - true if occurred error while file uploading. Read only.  檔案是否上傳錯誤,只讀
uploader {Object}: Reference to the parent Uploader object for this file. Read only.  上傳該檔案的Uploader ,只讀
方法
remove function() {: Remove this file from the queue  從上傳佇列移除該檔案
upload function() {: Upload this file  上傳該檔案
cancel function() {: Cancels uploading of this file  取消上傳該檔案
回撥函式
onBeforeUpload function() {: Fires before uploading an item.  上傳該檔案之前
onProgress function(progress) {: On file upload progress.  上傳該檔案的過程
onSuccess function(response, status, headers) {: On file successfully uploaded  成功上傳該檔案後
onError function(response, status, headers) {: On upload error  上傳該檔案出錯後
onCancel function(response, status, headers) { - On cancel uploading  取消上傳該檔案後
onComplete function(response, status, headers) {: On file upload complete (independently of the sucess of the operation)  完成上傳該檔案後
Filters(過濾器)
註冊過濾器:
var uploader =newFileUploader({
    filters: [{
        name:'yourName1',
        // A user-defined filterfn:function(item) {
            returntrue;
        }
    }]
});

接下說下我在專案中實際用到的檔案上傳!不周到的地方還望指教!!!

先看下實際效果:

html檔案程式碼:

Css樣式我就不貼了,你們可以自己定義!

    <div class="modal-header">
        <button type="button" class="close" ng-click="cancel()">×</button>
        <h4 class="modal-title fn-ms">{{title}}</h4>
    </div>

    <div class="panel-body">

        <a href="javascript:;"   class="file_a" >
            <input   type="file" name="file" nv-file-select="" uploader="uploader" multiple  />選擇檔案
        </a>
        <div class="col-md-12" style="margin-bottom: 20px">

            <h3>檔案上傳佇列</h3>
            <p>佇列長度: {{ uploader.queue.length }}</p>

            <table class="table" >
                <thead>
                <tr>
                    <th width="50%">檔名</th>
                    <th ng-show="uploader.isHTML5">檔案大小</th>
                    <th ng-show="uploader.isHTML5">進度</th>
                    <th>狀態</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr ng-repeat="item in uploader.queue">
                    <td><strong>{{ item.file.name }}</strong></td>
                    <td ng-show="uploader.isHTML5" nowrap>{{ item.file.size/1024/1024|number:2 }} MB</td>
                    <td ng-show="uploader.isHTML5">
                        <div class="progress" style="margin-bottom: 0;">
                            <div class="progress-bar" role="progressbar" ng-style="{ 'width': item.progress + '%' }"></div>
                        </div>
                    </td>
                    <td class="text-center">
                        <span ng-show="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
                        <span ng-show="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
                        <span ng-show="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
                    </td>
                    <td nowrap>
                        <button type="button" class="btn btn-success btn-xs" ng-click="item.upload()" ng-disabled="item.isReady || item.isUploading || item.isSuccess">
                            <span class="glyphicon glyphicon-upload"></span> 上傳
                        </button>
                        <button type="button" class="btn btn-warning btn-xs" ng-click="item.cancel()" ng-disabled="!item.isUploading">
                            <span class="glyphicon glyphicon-ban-circle"></span> 關閉
                        </button>
                        <button type="button" class="btn btn-danger btn-xs" ng-click="item.remove(this)">
                            <span class="glyphicon glyphicon-trash"></span> 刪除
                        </button>
                    </td>
                </tr>
                </tbody>
            </table>


            <div>
                <div>
                    進度:
                    <div class="progress" style="">
                        <div class="progress-bar" role="progressbar" ng-style="{ 'width': uploader.progress + '%' }"></div>
                    </div>
                </div>

                <button type="button" class="btn btn-success btn-s" ng-click="uploader.uploadAll()" ng-disabled="!uploader.getNotUploadedItems().length">
                    <span class="glyphicon glyphicon-upload"></span>上傳所有
                </button>
                <button type="button" class="btn btn-warning btn-s" ng-click="uploader.cancelAll()" ng-disabled="!uploader.isUploading">
                    <span class="glyphicon glyphicon-ban-circle"></span>關閉所有
                </button>
                <button type="button" class="btn btn-danger btn-s" ng-click="uploader.clearQueue()" ng-disabled="!uploader.queue.length">
                    <span class="glyphicon glyphicon-trash"></span> 刪除所有
                </button>
            </div>

        </div>

    </div>

    <div class="btn-group dropup" style="float: right">

    </div>
    <div class="panel-footer" style="text-align:center">
        <button type="button" class="btn btn-primary fn-ms"   ng-click="submit()">提交</button>
        <button type="button" class="btn btn-primary fn-ms"   ng-click="cancel()">關閉</button>
    </div>

重點說下js裡面的程式碼吧。

var uploader = $scope.uploader = new FileUploader({
    //最重要的!!!檔案流會出現在這裡,所以這裡就呼叫後臺的上傳檔案服務,將檔案流傳過去,詳細的FileUploader屬性上面有介紹。
});


// 回撥函式,這裡的回撥函式上面也有介紹。

uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/, filter, options) {
    console.info('onWhenAddingFileFailed', item, filter, options);
};
uploader.onAfterAddingFile = function(fileItem) {
//新增一個檔案到檔案佇列就會呼叫這個方法
};
uploader.onAfterAddingAll = function(addedFileItems) {
//檔案全部加入佇列後,就會呼叫這個方法
    console.info('onAfterAddingAll', addedFileItems);

};
//下面的一些目前專案中用到的不多,其實就是你想實現什麼功能,在上傳檔案的某一個時刻對應的那個回撥函式寫下你的邏輯就好
//比如你想上傳檔案裡面不能有重複的,你可以在過濾器裡面寫下你的邏輯,你也可以在每一個上傳檔案後的那個回撥函onAfterAddingFile//這裡寫下你的去重邏輯程式碼,過濾器程式碼我就沒貼了,裡面的一些具體邏輯還是自己實現比較好。
uploader.onBeforeUploadItem = function(item) {
    console.info('onBeforeUploadItem', item);
};
uploader.onProgressItem = function(fileItem, progress) {
    console.info('onProgressItem', fileItem, progress);
};
uploader.onProgressAll = function(progress) {
    console.info('onProgressAll', progress);
};
uploader.onSuccessItem = function(fileItem, response, status, headers) {
    console.info('onSuccessItem', fileItem, response, status, headers);
};
uploader.onErrorItem = function(fileItem, response, status, headers) {
    console.info('onErrorItem', fileItem, response, status, headers);
};
uploader.onCancelItem = function(fileItem, response, status, headers) {
    console.info('onCancelItem', fileItem, response, status, headers);
};
uploader.onCompleteItem = function(fileItem, response, status, headers) {
  
};
uploader.onCompleteAll = function(response) {

};

上面那些回撥函式,不太瞭解他的一些引數什麼的,你也可以像上面寫的那樣講那些引數在控制檯裡面打印出來,這樣理解起來就會清晰一些。

講解的不是太好,如果有什麼問題,希望可以一起討論 [email protected]