如何使用MongoDB上传文件

  1. jsp 页面 展示 图片的路径;

    标签内是上传的一些操作;div中的filequence,imgQuence 与上传方法中的id一致;
    input中的value用与上传 到mongodb数据库 ,及回显
    页面的写法多种:这里只提供两种 ;灵活使用

<tr>
         <td>
         <img width='50px' height='50px' src='../mongodb/findImgById.do?imgId=${projectBean.img}'>
         </td>
         <td>
           <input  type="file"   id="file_upload" >
		          <p>
						<a class="easyui-linkbutton" data-options="iconCls:'icon-ok'"
							href="javascript:$('#file_upload').uploadify('upload', '*')">开始上传所有任务</a>
						<a class="easyui-linkbutton" data-options="iconCls:'icon-lock'"
							href="javascript:$('#file_upload').uploadify('stopa')">停止上传</a>
						<a class="easyui-linkbutton" data-options="iconCls:'icon-ok'"
							href="javascript:$('#file_upload').uploadify('upload')">上传</a>
						<a class="easyui-linkbutton" data-options="iconCls:'icon-lock'"
							href="javascript:$('#file_upload').uploadify('cancel')">取消上传</a>
					</p>
				<div id="filequence">
				</div>
				<div id="imgQuence">
				</div> 
		      <input type="hidden" id="imgId"  name="img" value="${projectBean.img}" >
         </td> 
     </tr>
     或者
    <input type="text" id="hideImg" name="img"> 
    <input type="file" class="projectfile" name="file" id="imgId" >
  1. id 与上面的input中id相对应 使用file 来上传文件; 这里比较灵活 可以使用其他插件 ,知道传的值 需要的值就可以了
$("#file_upload").uploadify({
	'swf'     : '${pageContext.request.contextPath}/uploadify/privateUpload/uploadify.swf',//按钮的动画
	'uploader': '${pageContext.request.contextPath}/mongodb/imgUpload.do',  // 后台请求路径
	'cancelImg': 'image/uploadify', //uploaddify 图片
	'queueID' :'filequence',  //  存放序列的地方
	'method'  : 'post',			
	'fileObjName' : 'suppImg',     //和后台 属性名字一样
	'sizeLimit':30,
	'progressData' :'percentage', //  设置上传进度显示方式,percentage显示上传百分比,speed显示上传速度
	'auto':false,   //是否自动  上传
	'multi': false,  //是否选择多个
	'removeCompleted' : false,// 上传完是否自动删除任务
	'fileSizeLimit': 0, // "4MB"  写0的话就是对 他不做限制
	'buttonText' :  '上传照片',
	'buttonCursor': 'head', // 光标的样子
	'fileTypeDesc' : 'mp4/avi/kux', // 你得告知  上传者    可以上传  什么类型的吧  与下面的那个属性连用
	'fileTypeExts' : '*.bmp;*.jpg',//  告诉 uploadify可以上传  什么类型的
	'uploadLimit': 1, //设置   上传时的上传文件数       超过就会触发 on
	//'onSelectError':uploadErrorMsg,
	'onUploadSuccess': function (file,data,response){    //  上传成功后   将信息  给指定的位置
	var img=	JSON.parse(data);
	alert(img.imgId);
		$("#imgId").val(img.imgId);
		},
'onUploadError' :function (file, errorCode, errorMsg, errorString){
	alert("只能上传一个");	
		},
});	
  1. Controller service层 中的参数及返回值需要特别注意;

    	 a. 上传
    	  //图片 controller 上传   返回   HashMap<String, Object>
    	  @RequestMapping("imgUpload")
    		@ResponseBody
    		public  HashMap<String, Object>  imgUpload(@RequestParam(value = "suppImg", required = false) MultipartFile file,
    		HttpServletRequest request,HttpServletResponse response){
    			return  mongoDBService.uploadImg(file);
    		}
          //图片 service 上传    返回的是图片的ID     与 图片的 名称;
             @Override
    	    public HashMap<String, Object> uploadImg(MultipartFile file) {
    		GridFS gridFS=new GridFS(mongoTemplate.getDb());
    		String id= UUID.randomUUID().toString();
    		String filename = file.getOriginalFilename();
    		HashMap<String, Object> map=new HashMap<>();
    		try {
    				GridFSInputFile createFile = gridFS.createFile(file.getInputStream());
    				createFile.setId(id);
    				createFile.setFilename(filename);
    				createFile.save();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    			map.put("imgId", id);
    			map.put("fileName", filename);
    			return map;
    		}
             b.  查找图片          Controller 层 
             //查找图片 去mongodb数据库
               @RequestMapping("findImgById")
    			public  void  	findImgById(String imgId,HttpServletResponse response){
    				GridFSDBFile file =	mongoDBService.findImgById(imgId);
    				try {
    					if(file!=null){
    						response.setContentType("application/octet-stream"); 
    						ServletOutputStream sos= response.getOutputStream();
    						 file.writeTo(sos);
    						 sos.flush();  //输出
    				                 sos.close();  
    					}
    				} catch (IOException e) {
    					e.printStackTrace();
    				}					
              }
    
              //去mongo查图    service层   传图片Id来查找图片
    				@Override
    				public GridFSDBFile findImgById(String imgId) {
    					DBObject query  = new BasicDBObject("_id", imgId); 
    					GridFS gridFS=new GridFS(mongoTemplate.getDb());
    					 GridFSDBFile findOne = gridFS.findOne(query);
    					return findOne;
    				}
    

猜你喜欢

转载自blog.csdn.net/cxy_chh/article/details/89326655