Java examples for Big Data:MongoDB
Insert file to mongodb via GridFS
import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.MongoClient; import java.net.UnknownHostException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import com.mongodb.BasicDBObject; import com.mongodb.BulkWriteOperation; import com.mongodb.Cursor; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSInputFile; import java.util.List; import java.util.Set; import javax.swing.JOptionPane; import java.sql.*; import java.io.*; import java.util.*; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class FileUploader extends javax.swing.JFrame { private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try {// w w w. j a v a 2 s.c om MongoClient m = new MongoClient("localhost", 27017); DB db = m.getDB("mydb"); File file = jFileChooser1.getSelectedFile(); String path = jFileChooser1.getSelectedFile().getPath(); System.out.println(path); GridFS gf = new GridFS(db, "Attachment"); GridFSInputFile gfsFile = gf.createFile(file); gfsFile.setFilename(file.getName()); long timeBefore = System.nanoTime(); gfsFile.save(); long timeAfter = System.nanoTime() - timeBefore; jTextField2.setText("" + timeAfter); } catch (Exception e) { e.printStackTrace(); } } }