1. 程式人生 > >mongodb檔案上傳和讀取檔案

mongodb檔案上傳和讀取檔案

@Autowired
private GridFsOperations operations;
/**
	 * 儲存圖片
	 * 
	 * @param file
	 * @param fileName
	 * @throws IOException
	 */
	private void saveGridFSImage(MultipartFile file, String fileName) throws IOException {
		operations.store(file.getInputStream(), fileName);
	}

	/**
	 * 刪除圖片
	 * 
	 * @param filename
	 */
	private void delImage(String fileName) {

		operations.delete(new Query(Criteria.where("filename").is(fileName)));
	}

	/**
	 * 判斷照片會否存在
	 * 
	 * @param filename
	 * @return
	 */
	private boolean hashNextImg(String fileName) {
		GridFSFindIterable result = operations.find(new Query(Criteria.where("filename").is(fileName)));
		return result.iterator().hasNext();
	}

	/**
	 * 根據name查詢圖片
	 * 
	 * @param fileName
	 * @return
	 */
	private GridFsResource getImgInput(String fileName) {
		return operations.getResource(fileName);

	}