1. 程式人生 > >Java專案中對MongoDB資料庫進行檔案上傳

Java專案中對MongoDB資料庫進行檔案上傳


import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.UUID;

public class MongoDBTest {
	private static Logger log = LoggerFactory.getLogger(MongoDbUtil.class);

	private static final class MongoInstance {
		public final static MongoClient client;
		static {
			client = new MongoClient("localhost", 27017);
		}
	}

	public static MongoDatabase getDatabase(String databaseName) {
		return MongoInstance.client.getDatabase(databaseName);
	}

	/**
	 * 上傳檔案
	 * @param file
	 * @param databaseName
	 * @return
	 */
	public static String uploadFileToGridFS(File file,String databaseName) {
		InputStream in = null;
		String returnId = null;
		String pathName = file.getPath();
		String[] pathNameArray = pathName.split("\\\\");
	    String[] name = pathNameArray[pathNameArray.length-1].split("\\.");
		String filename = name[0];
		String type = name[name.length-1];
		try {
			in = new FileInputStream(file);
			GridFSBucket bucket = GridFSBuckets.create(getDatabase(databaseName));
			GridFSUploadOptions options = new GridFSUploadOptions();
			//設定除filename以為的其他資訊
			Document metadata = new Document();
			metadata.append("contentType", type);
			options.metadata(metadata);
			ObjectId fileId = bucket.uploadFromStream(filename+type, in,options);
			returnId = fileId.toHexString();
			log.info("檔案上傳成功");
		} catch (IOException e) {
			log.info("upload fail:" + e);
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				log.info("close inputstream fail:" + e);
			}
		}
		return returnId;
	}

	/**
	 * 通過objectid和file下載檔案
	 * @param objectId
	 * @param file
	 * @param databaseName
	 */
	public static void downloadFile(String objectId, File file,String databaseName) {
		OutputStream os = null;
		try {
			os = new FileOutputStream(file);
			GridFSBucket bucket = GridFSBuckets.create(getDatabase(databaseName));
			bucket.downloadToStream(new ObjectId(objectId), os);
			log.info("檔案下載成功");
		} catch (IOException e) {
			log.info("download fail:" + e);
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					log.info("close outputstream fail:" + e);
				}
			}
		}
	}

	/**
	 * 通過objectid刪除檔案
	 * @param objectId
	 * @param databaseName
	 */
	public static void deleteByObjectId(String objectId,String databaseName) {
		GridFSBucket bucket = GridFSBuckets.create(getDatabase(databaseName));
		bucket.delete(new ObjectId(objectId));
		log.info("檔案刪除成功");
	}
	
	
	/**
	 * 查詢檔案
	 * @param databaseName
	 */
	public static List find(String databaseName){
		GridFSBucket bucket = GridFSBuckets.create(getDatabase(databaseName));
		GridFSFindIterable iterable = bucket.find();
		MongoCursor mongoCursor= iterable.iterator();
		List results = new ArrayList(); 
		while(mongoCursor.hasNext()){
			results.add(mongoCursor.next());
		}
		return results;
	}
	
	/**
	 * 查詢檔案
	 * @param databaseName
	 */
	public static List findBy(String databaseName,Bson filter){
		GridFSBucket bucket = GridFSBuckets.create(getDatabase(databaseName));
		GridFSFindIterable iterable = bucket.find(filter);
		MongoCursor mongoCursor= iterable.iterator();
		List results = new ArrayList(); 
		while(mongoCursor.hasNext()){
			results.add(mongoCursor.next());
		}
		return results;
	}
}
import java.io.File;
import org.junit.Test;

public class MongoGridFSTest 
{
    
    /**
	 * 先上傳
	 */
    @Test
	public void upload() {
		File file = new File("C:/Users/Administrator/Desktop/Java持久化之myBatis3.pdf");
		String databaseName = "test";
		String objectId = MongoDbFSUtil.uploadFileToGridFS(file,databaseName);
		System.out.println(objectId);
		System.out.println("檔案上傳成功");
	}

	/**
	 * 測試下載
	 */
    @Test
	public void download() {
		//System.out.println(objectId);
		File file = new File("D:/1.pdf");
		String databaseName = "test";
		MongoDbFSUtil.downloadFile("594b8298932ed623249dea18", file,databaseName);
		System.out.println("檔案下載成功");
	}

	/**
	 * 最後將上傳的資訊刪除
	 */
    @Test
	public void delete() {
		String databaseName = "test";
		MongoDbFSUtil.deleteByObjectId("594b3b53932ed60b043ac4c8",databaseName);
	}
	
	 
    @Test
    public void find(){
    	List results= MongoDbFSUtil.find("test");
    	for(GridFSFile file: results){
    		System.out.println(file.toString());
    	}
    }
    

    @Test
    public void findBy(){
    	Document filter = new Document();
    	filter.append("filename", "深入理解Java虛擬機器:JVM高階特性與最佳實踐.pdf");
    	List results= MongoDbFSUtil.findBy("test",filter);
    	for(GridFSFile file: results){
    		System.out.println(file.getId());
    	}
    }
    
   
    
   
}