【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" onclick="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中存在相同文件,则先将其删除,然后再保存。

你可能感兴趣的:(mongodb)