Uploading and Storing Images in MongoDB via Web Browser

MongoDB is known as a NoSQL database, which uses a JSON-like document structure by key-value pairs. Comparing to the relational database like MySQL, MongoDB is easier and more scalable. Especially when processing big and complex data, MongoDB can perform faster and better. In this tutorial, let’s take a glimpse of how to upload and save scanned images to MongoDB.

dwt_mongodb

Scanning and Uploading Documents with DWT

To create a Web TWAIN scanning application, you can read the article How to Build Web Scanning Application with Gradle that I shared a couple of weeks ago. We can import the source code and resources to NetBeans for easily coding and testing.

Create a new project and select Web Application in NetBeans:

netbeans_new

Create web.xml:

netbeans_web

Create Java package:

netbeans_package

Copy all relevant source code and resources to your NetBeans project:

netbeans_project

Based on the source code, let’s make a little bit of change for MongoDB.

Storing Image Data to MongoDB

Download MongoDB and MongoDB Java driver.

Add mongo-java-driver-3.0.0.jar to your project:

netbeans_jar

Create a Java class FileManager, and add the following methods:

public class FileManager {

    public void saveToDb(ServletContext context, HttpServletResponse response, InputStream in, String fileName) {
        if (in == null) {
            return;
        }

        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException ex) {
            Logger.getLogger(FileManager.class.getName()).log(Level.SEVERE, null, ex);
            return;
        }

        try {
            MongoClient mongoClient = new MongoClient("localhost"); // connect to mongodb
            DB db = mongoClient.getDB("dynamsoft");                 // get database

            GridFS fs = new GridFS(db, "twain");                    // GridFS for storing images

            GridFSInputFile file = fs.createFile(in, fileName);
            file.setContentType("image");
            file.save();
            writer.println(file.toString());
            mongoClient.close();                                   // close all resources
        } catch (Exception e) {
            writer.println("database exception");
        }

    }
}

GridFS is used for storing and retrieving files that exceed the BSON-document size limit of 16MB. When the Web server Tomcat receives the uploading request, we can save the image data to MongoDB in processRequest():

protected void processRequest(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        // Create path components to save the file
        final Part filePart = request.getPart("RemoteFile");
        final String fileName = getFileName(filePart);

        FileManager manager = new FileManager();
        manager.saveToDb(getServletContext(), response, filePart.getInputStream(), fileName);
//        manager.saveToDisk(getServletContext(), response, filePart.getInputStream(), fileName);
    }

Now, you can test the Web application with the following steps:

  1. start up MongoDB
  2. run the project
  3. Open http://localhost:8080/DWT/

Source Code

https://github.com/dynamsoft-dwt/MongoDB-Documents-Upload