Springmvc与Mongo GridFs 实现文件的上传和获取

Springmvc与Mongo GridFs 实现文件的上传和获取 ,最常见的情景莫过于手机客户端实现头像上传


上传文件,代码片段一:

	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public Object uploadFile(HttpServletRequest request) {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 先判断request中是否包涵multipart类型的数据,
		String fileUrl = "";
		if (multipartResolver.isMultipart(request)) {
			// 再将request中的数据转化成multipart类型的数据
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile((String) iter.next());
				if (file != null) {
					try {
						GridFSInputFile inputFile = fileService.save(file.getInputStream(), file.getOriginalFilename());
						if (inputFile == null) {
							return StatusConfig.FileUploadError;
						} else {
							fileUrl = inputFile.getId().toString();
						}
					} catch (IllegalStateException | IOException e) {
						
					}
				}
			}
			HashMap<String, Object> hashMap = new HashMap<String, Object>();
			fileUrl = this.getHttpFilePath() + fileUrl;
			hashMap.put(ConstantsKey.STATUS, 200);
			hashMap.put(ConstantsKey.DATA, fileUrl);
			String json = ConvertUtils.as().toJson(hashMap);
			System.out.println("photourl:" + json);
			return json;
		} else {
			
		}
	}
上传文件,代码片段二:

	@Autowired
	private MongoDbFactory mongodbfactory;
	/**
	 * 用给出的id,保存文件,透明处理已存在的情况
	 * id 可以是string,long,int,org.bson.types.ObjectId 类型
	 * @param in
	 * @param id
	 */
	public GridFSInputFile save(InputStream in, Object id){
		GridFS gridFS = new GridFS(mongodbfactory.getDb());
		GridFSInputFile gridFSInputFile = gridFS.createFile(in);
		gridFSInputFile.save();
		return gridFSInputFile;
	}

通过Http请求文件

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public void getFile(@PathVariable String id, HttpServletResponse response) {
		GridFSDBFile file = fileService.getById(new ObjectId(id));
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			os.write(FileUtils.readInputStream(file.getInputStream()));
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

请求文件代码片段2:

	
	/**
	 * 据id返回文件
	 */
	public GridFSDBFile getById(Object id){
		DBObject query  = new BasicDBObject("_id", id);
		GridFS gridFS = new GridFS(mongodbfactory.getDb());
		GridFSDBFile gridFSDBFile = gridFS.findOne(query);
		return gridFSDBFile;
	}





评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值