日期:2014-05-16 浏览次数:20447 次
import java.io.File; import java.net.UnknownHostException; import com.mongodb.DB; import com.mongodb.Mongo; import com.mongodb.MongoException; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSDBFile; import com.mongodb.gridfs.GridFSInputFile; public class Show { public static void main(String[] args) throws UnknownHostException, MongoException { Mongo host = new Mongo("localhost"); DB db = host.getDB("demo"); db.addUser("admin", "admin".toCharArray()); boolean auth = db.authenticate("admin", "admin".toCharArray()); if (auth) { String file, newFilename, bucket, saveTo; bucket = "fs"; newFilename = "image1"; file = "e:/2.jpg";// 本地文件路径 saveTo = "e:/images/2.jpg"; db.requestStart(); try { // ----------文件保存 File files = new File(file); GridFS gfs = new GridFS(db, bucket); GridFSInputFile gfsInput = gfs.createFile(files); gfsInput.setFilename(newFilename); gfsInput.setContentType(""); gfsInput.save(); db.requestDone(); // 文件读取,并保存成新的文件名saveTo GridFSDBFile dbFile = gfs.findOne(newFilename); if (dbFile != null) System.out.println("file size:" + dbFile.writeTo(saveTo)); // 删除数据库中的文件 //gfs.remove(newFilename); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }?
?
?
?