【MongoDB】上傳示例

今天結合項目說一下上傳音頻到MongoDB的步驟。

首先,頁面就簡單畫了一個file類型的文件,和一個提交按鈕。

這裏寫圖片描述

代碼如下:

<input type="file" id="file" name="file"  style="display:-webkit-inline-box;width: 180px;"/>
<input id="addAudioSubmit" type="button" style="width: 70px; position: relative; bottom: 21px; left: 140px;" src="image/backGroup.png" οnclick="uploadFile(this)" value="添加音頻">

當點擊按鈕的時候,在Js中觸發的方法:

 /**
  * 上傳音頻文件 
  * @param formTag
  */
 function uploadFile(formTag){

     var path="/ImportMongoVideo?paperMainId=" + $("#paperMainId").val();
     $.ajaxFileUpload({ 
     method:"POST",
             url:ctx + path,            //需要鏈接到服務器地址  
             secureuri:true,  
             fileElementId:'file',                        //文件選擇框的id屬性 
             success: function(data, status){ 
                 msg:'添加音頻成功!';
             },error: function (data, status, e){ 
                 msg:'添加音頻失敗,請稍後重試';
             }  
         });
     }

那接下來看controller中的方法。

    /**
     * 導入音頻 
     * @param file
     * @param request
     * @param response
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("ImportMongoVideo")
    public void ImportMongoVideo(
            @RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request, HttpServletResponse response)
            throws UnsupportedEncodingException {

        String dataBaseName = (String) request.getSession().getAttribute(
                CloudContext.DatabaseName);

        // 通過shiro+cas,這裏可以得到用戶的Id
        String usercode = (String) request.getSession().getAttribute("name");// usercode

        dataBaseName = "itoo_exam";// 這個後期加入shiro是要刪除的

        String paperMainId = request.getParameter("paperMainId");

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        MultipartFile file1 = multipartRequest.getFile("file");

        String fileName = file.getOriginalFilename();
        String logoRealPathDir = request.getSession().getServletContext()
                .getRealPath(fileName);

        File localFile = new File(logoRealPathDir);

        try {
            file1.transferTo(localFile);
        } catch (IllegalStateException | IOException e) {
            logger.error("PaperManagerController中ImportMongoVideo對象轉換json失敗+ savePaperMain: %s%n" + e.getMessage());

        }

        String pictureID = UUID.randomUUID().toString();

        LinkedHashMap map = new LinkedHashMap();

        String MongodbName = "exam";
        String collectionName = "dd";
        MongoUtil mongoUtil = new MongoUtil();
        PaperMain paperMain = new PaperMain();
        try {
            mongoUtil.uploadFile(localFile, pictureID, MongodbName, collectionName,
                    map);
            paperMain = paperMainBean.queryPaperMainById(paperMainId,
                    dataBaseName);
        } catch (Exception e) {
            logger.error("PaperManagerController中ImportMongoVideo裏mongoUtil.uploadFile調用 方法失敗: %s%n" + e.getMessage());

        }
        paperMain.setAudio(pictureID);
        paperMain.setDataBaseName(dataBaseName);
        paperMainBean.updateEntity(paperMain);

        // 如果上傳的文件成功,則將上傳的文件在服務器中刪除,防止服務器中音頻文件導致服務器內存變小
        if (localFile.isFile()) {
            localFile.delete();
        }
    }

從實現上來說,上面最關鍵的一步是MongoUtil 這個類調用uploadFile方法。

/**
     *  @MethodName : uploadFile
     * @Description : 上傳文件
     * @param file :文件,File類型
     * @param id    :唯一標示文件,可根據id查詢到文件.必須設置
     * @param dbName :庫名,每個系統使用一個庫
     * @param collectionName:集合名,如果傳入的集合名庫中沒有,則會自動新建並保存
     * @param map:放入你想要保存的屬性,例如文件類型(“congtentType”".jpg"),字符串類型,區分大小寫,如果屬性沒有的話會自動創建並保存
     */
   public void uploadFile(File file ,String id,String dbName,String collectionName,LinkedHashMap<String, Object> map){
       //把mongoDB的數據庫地址配置在外部。
        try {
            Mongo mongo =getMongo(); 
            //每個系統用一個庫
            DB db= mongo.getDB(dbName);
            System.out.println(db.toString());
            //每個庫中可以分子集
            GridFS gridFS= new GridFS(db,collectionName);

            // 創建gridfsfile文件
            GridFSFile gridFSFile = gridFS.createFile(file);
            //判斷是否已經存在文件,如果存在則先刪除
            GridFSDBFile gridFSDBFile=getFileById(id, dbName, collectionName);
            if(gridFSDBFile!=null){
                deleteFile(id, dbName, collectionName);
            }
            //將文件屬性設置到
            gridFSFile.put("_id", id);
            //循環設置的參數
            if (map != null && map.size() > 0) {
                for (String key : map.keySet()) {
                    gridFSFile.put(key, map.get(key));
                }
            }
            //保存上傳
            gridFSFile.save();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

項目中做上傳的時候,是新生成了一個GUID作爲音頻上傳到MongoDB的ID。同時將ID保存到自己的業務庫中。
在 上傳的時候,獲取到這個待上傳的文件,通過流文件的形式先將文件保存到服務器中。然後將文件上傳到MongoDB中,上傳過程如果發現MongoDB中存在相同文件,則先將其刪除,然後再保存。

發佈了199 篇原創文章 · 獲贊 122 · 訪問量 38萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章