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.


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:


Create web.xml:


Create Java package:


Copy all relevant source code and resources to your 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:


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) {

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

        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);
            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 {

        // 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