Node.js 切近實戰(八) 之Excel在線(文件權限)

最近美國又他媽的皮癢了,在南海找事,還說什麼中國必須接受南海仲裁結果,我去你大爺的,你覺得你是誰啊。說實話只要咱們要決一雌雄的勇氣,還管什麼華盛頓航母,佛吉尼亞潛艇,大不了你們一塊兒死,不,全世界一塊兒死。怎麼個死法,中國惹急了先給俄羅斯來幾顆核彈,而後俄羅斯反擊中國的同時,也會給歐洲扔幾顆核彈,給美國扔不少核彈,而後歐洲英法會給其餘國家扔核彈,美國給世界扔核彈,俄羅斯只給北冰洋扔就好了,中國給美國和太平洋扔就好了,這樣世界就不復存在了。mysql

 

今天咱們來看一下文件權限管理,這個實際上是對共享出去的文件的一個簡單的權限管理demo。在上節我寫過的界面中,能夠查詢本身共享出去的文件。ajax

wKiom1d_uvjwLs_IAABtoZkX9S0247.png

勾選Shared,咱們查出本身共享出去的文件。或者咱們能夠經過點擊ToolBar上面的SHARE按鈕,實現共享文件。sql

1mongodb

2數據庫

3json

4api

5數組

6微信

7mvc

8

9

10

11

12

13

14

15

16

$(".k-grid-share""#file_list").bind("click"function (ev) {

    var selIds = [];

    $("#file_list table:eq(1)").find("tr").each(function () {

        var chkElement = $(this).children("td:first").find("input[type='checkbox']").first();

        if (chkElement.prop('checked')) {

            selIds.push(chkElement.val());

        }

    });

     

    if (selIds.length == 0) {

        showMsg('info''Please select at least one file to share!');

        return;

    }

     

    sharedUpdate(selIds, true);

});

首先是找到選中的文件的_id,而後調用shareUpdate方法去共享。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

function sharedUpdate(selIds, shared) {

    msg = Messenger().post({

        message: "Do you want to " + (shared? 'share':'unshare') + " these file?",

        actions: {

            delete: {

                label: 'Yes',

                delay: 10,

                action: function () {

                    var postData = {

                        ids: selIds,

                        isShared: shared

                    };

                     

                    $.ajax({

                        url: '/file/share'

                        type: 'PUT'

                        dataType: 'json',

                        data: { postData: JSON.stringify(postData) },

                        success: function (res) {

                            if (!res.isSuc) {

                                showMsg('error', res.msg);

                                return;

                            }

                             

                            getFilelist(selGroupId);

                        }

                    });

                    msg.hide();

                }

            },

            cancel: {

                label: "No",

                action: function () {

                    msg.hide();

                }

            }

        }

    });

}

發送一個ajax請求,去修改傳入文件的共享屬性,看一下效果

wKiom1d_vNvTamX7AAASDfy2Q4A040.png

先會彈出確認,點擊Yes,調用api file/share去修改共享屬性,看一下後臺。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

router.put('/file/share', fileRoutes.fileShare);

exports.fileShare = function (req, res) {

    var data = JSON.parse(req.body.postData);

    var idArray = data.ids;

     

    if (!idArray || idArray == 0) {

        res.status(403).json(commonMsgRes.buildJsonErrorRes('NoRecord'));

        return;

    }

     

    fileModel.update({ _id: { $in: idArray } }, { $set: { isshared: data.isShared } }, { multi: true }

function (error, result) {

        if (error) {

            res.json({ isSuc: false, msg: error.message });

        }

        else {

            res.json({ isSuc: true });

        }

    });

}

在後臺,先把json字符串轉化成js對象,而後用mongoose提供的update方法去批量更新數據。注意這裏的$in,實際上是和sqlServer中的in一個意思,$set意思是須要修改的屬性,你能夠在這裏寫多個屬性進行修改,並不必定只是一個isshared屬性,而後最後的multi:true,意思是更新多個doc。因此整個修改的意思就是找到_id在idArray中的file docs,而後將其isshared屬性所有修改成傳入的值。固然在這裏你也可使用mongoose中的findAndUpdate方法去作批量更新。

 

文件share好以後,咱們看一下共享文件權限設置界面。

wKioL1d_wjHQRRJAAACeCc0GwYw849.png

 

查詢出數據後,每一個文件均可以設置權限,這裏很簡單的三個,要真作權限,仍是買吉日嘎啦的走火入魔權限管理系統好了,本身不要瞎折騰。OK,那麼這三個權限使咱們mongodb數據庫中配置的。

wKiom1d_wtPiluekAABhd0NeFyQ395.png

 

咱們在界面能夠選擇一個或者多個。

wKioL1d_wwayubJzAABALF21hNg124.png

選擇完成後,點擊Save,若是不想修改了,點擊cancel,能夠回到初始狀態,咱們來看一下js代碼。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

$("#file_list").kendoGrid({

    scrollable: true,

    allowCopy: true,

    resizable: false,

    sortable: true,

    height: 800,

    pageable: {

        refresh: true,

        pageSizes: [10, 20, 50, 100],

        buttonCount: 5,

    }, 

    toolbar: [{ name: 'authSet', text: "Batch Setup" , imageClass: 'k-icon k-i-lock' }],

    columns: [{

            template: "<div class='center-align-text'>" +

                "<input id='chkId_#=_id#' type='checkbox' class='k-checkbox' value='#=_id#' onclick='chkHeader_cl

                + "<label class='k-checkbox-label' for='chkId_#=_id#'></label></div>",

            field: "",

            title: "<div class='center-align-text'>" +

                "<input type='checkbox' class='k-checkbox' id='chk_all'/>" 

                + "<label class='k-checkbox-label' for='chk_all'></label></div>",

            width: 45,

            sortable: false

        },

        {

            field: "fullname", 

            title: "File Name"

        },

        {

            field: "isshared", 

            title: "Shared" ,

            template: '<select id="ddl_auth#=_id#" name="auth" multiple="multiple"></select>',

            sortable: false

        }, {

            command: [

                {

                    name: "authUpdate",

                    text: "Save",

                    imageClass: "k-icon k-i-tick",

                    click: updateFileAuth

                }, {

                    name: "authCancel",

                    text: "Cancel",

                    imageClass: "k-icon k-i-undo",

                    click: cancelUpdateFileAuth

                }

            ], 

            width: 230,

            title: "Operation"

        }], dataBound: function (rowBoundEvent) {

        $("#file_list select[name='auth']").each(function (index, element) {

            $(element).kendoMultiSelect({

                valuePrimitive: true,

                placeholder: "---Please Select---",

                ignoreCase: true,

                dataSource: authArray.length > 0? authArray:dataSource,

                dataTextField: "name",

                dataValueField: "_id",

                headerTemplate: '<div class="multi-select-header">' 

                            + 'Choose File Auth Below:</div>',

                dataBound: function (e) {

                    var dataItem = $("#file_list").data('kendoGrid').dataItem($(element).closest("tr"));

                    if (dataItem.auth && dataItem.auth.length > 0) {

                        var authArray = [];

                        dataItem.auth.forEach(function (v) {

                            authArray.push(v._id);

                        });

                         

                        this.value(authArray);

                    }

                     

                }

            });

        });

    }

});

你們注意isShared這一列,是個下拉列表,支持多選,而後在數據綁定完成之後,循環裏面的下拉列表,將其渲染成kendoMultiSelect,注意這裏的dataSource參數,若是authArray已經取到了,則使用,不然調用後臺api獲取。

1

2

3

4

5

6

7

8

var dataSource = new kendo.data.DataSource({

    transport: {

        read: {

            url: "/file/auth",

            dataType: "json"

        }

    }

});

若是在這裏直接使用每次請求的話,會存在不少問題,性能問題,界面渲染也會出現一些重複渲染的問題。由於你們的auth都是同樣的,因此咱們先取到再說。

1

2

3

4

var authArray = [];

$.get('/file/auth'function (result) {

    authArray = result;

});

OK,接下來咱們看一下Save功能,在grid的定義中,咱們能夠看到save調用的是updateFileAuth方法。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

function updateFileAuth(e) {

    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));

    var fileId = dataItem._id;

    var authArray = $("#ddl_auth" + dataItem._id).data("kendoMultiSelect").value()

     

    if (!authArray || authArray.length == 0) {

        showMsg('info''Please select at least one auth!');

        return;

    }

     

    var postData = {

        fileId: dataItem._id,

        fileAuth: authArray

    };

     

    $.post('/file/auth', postData, function (res) {

        if (!res.isSuc) {

            showMsg('error', res.msg);

            return;

        }

         

        showMsg('success''Saved successfully!');

        $("#btn_searchShared").click();

    });

}

根據當前行拿到id,再根據id拿到下拉選中的值,kendoMultiSelect的value方法返回的就是一個數組。

最後咱們將獲得的數組傳遞到api去修改權限,看一下後臺。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

router.post('/file/auth', fileAuthRoutes.updateFileAuth);

exports.updateFileAuth = function (req, res) {

    var fileId = req.body.fileId;

    var fileAuth = req.body.fileAuth;

    var fileAuths = [];

     

    fileAuth.forEach(function (v) {

        fileAuths.push(mongoose.Types.ObjectId(v));

    });

     

    fileModel.findByIdAndUpdate(fileId, { '$set': { auth: fileAuths } }

        function (error, doc) {

        console.log(error);

        if (error) {

            res.json({ isSuc: false, msg: error.message });

        }

        else {

            res.json({ isSuc: true });

        }

    });

}

在這裏咱們先將權限的id轉化成ObjectId,再根據傳入的文件id進行修改,ok,save就說完了。

再看一下cancel,其實就是將該行的權限id再賦給下拉列表。

1

2

3

4

5

6

7

8

9

10

11

function cancelUpdateFileAuth(e) {

    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));

    var fileId = dataItem._id;

    var authArray = [];

    if (dataItem != null && dataItem.auth.length > 0) {

        dataItem.auth.forEach(function (v) {

            authArray.push(v._id);

        });

    }

    $("#ddl_auth" + dataItem._id).data("kendoMultiSelect").value(authArray);

}

ok,最後就是batch批量設置,勾選數據,點擊ToolBar上的BATCH SETUP,咱們先看頁面的代碼。

wKiom1d_yLTx06NTAACSmsMSEe0041.png

這裏的fileAuth_Window就是批量設置界面,在這裏你們發現了一個循環的寫法,不錯,這就是jade模板中的語法,相似於razor視圖引擎同樣。看到這樣的循環,咱們在後臺必須有代碼要給頁面這些值,相似於asp.NET mvc中頁面綁定的Model。

1

2

3

fileAuthSchemas.authModel.find({}, function (error, doc) {

    res.render('authorization/docauth', { authArray: doc });

});

看到了吧,在向客戶端輸出頁面時,同時傳了一個對象,對象中的authArray的值爲doc。這樣的話,咱們就能夠在頁面直接使用這個變量authArray。

wKioL1d_yk7SDrZWAAAZgiCtUAQ554.png

咱們選擇三個,點擊SETUP,AJAX調用後臺api批量設置。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

$("#btn_setup").click(function () {

    var selAuthIdArray = getSelAuthId();

    if (selAuthIdArray.length == 0) {

        showMsg('info''Please select at least one auth!');

        return;

    }

     

    var selIds = getSelFileId();

    if (selIds.length == 0) {

        showMsg('info''Please select at least one file to setup!');

        return;

    }

     

    showConfirm(updateFileAuthBatch);

});

 

function updateFileAuthBatch() {

    var selIds = getSelFileId();

    if (selIds.length == 0) {

        showMsg('info''Please select at least one file to setup!');

        return;

    }

     

    var postBody = {

        fileIdArray: selIds,

        fileAuth: getSelAuthId()

    };

     

    $.post('/file/auth/batch', postBody, function (result) {

        if (!result.isSuc) {

            showMsg('error', result.msg);

            return;

        }

 

        fileAuthWindow.data("kendoWindow").close();

        $("#btn_searchShared").click();

    });

}

 

function showConfirm(action) {

    msg = Messenger().post({

        message: "Do you want to setup?",

        actions: {

            save: {

                label: 'Yes',

                delay: 10,

                action: function () {

                    action();

                    msg.hide();

                }

            },

            cancel: {

                label: "No",

                action: function () {

                    msg.hide();

                }

            }

        }

    });

}

上面這段代碼有沒有很像C#中的委託呢?有點。最後咱們看一下後臺的批量設置api代碼。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

exports.batchUpdateFileAuth = function (req, res) {

    var fileIdArray = req.body.fileIdArray;

    var fileAuth = req.body.fileAuth;

    var fileAuths = [];

     

    if (!fileIdArray || fileIdArray.length == 0) {

        res.json(commonMsgRes.buildJsonErrorRes('NoRecord'));

        return;

    }

     

    fileAuth.forEach(function (v) {

        fileAuths.push(mongoose.Types.ObjectId(v));

    });

     

    fileModel.update({ _id: { $in: fileIdArray } }, { $set: { auth: fileAuths } }, { multi: true }

        function (error, doc) {

        if (error) {

            res.json({ isSuc: false, msg: error.message });

        }

        else {

            res.json({ isSuc: true });

        }

    });

}

這樣就設置成功了,咱們來看一下效果。

wKioL1d_y36AsYJMAACdV_6SYNc024.png

 

好了,下節進入咱們的關鍵點,Excel在線保存,編輯。

 

結束語

 

免費學習更多精品課程,登陸樂搏學院官網http://h.learnbo.cn/

或關注咱們的官方微博微信,還有更多驚喜哦~

 

本文出自 「技術創造價值」 博客,請務必保留此出處http://leelei.blog.51cto.com/856755/1812777

相關文章
相關標籤/搜索