Days
Hours
Minutes
Seconds
x

Froala Editor v4.1.3 is Here LEARN MORE

Skip to content

Java

Image Upload

The following sections describe how to handle image uploads on your server using Java as a server-side language. For information on the upload workflow refer to the image upload documentation.

Dependencies

The java image upload example requires the following dependencies:

Frontend

This is the HTML that you need to include in the WebContent folder:

  1. On the head section include the Editor style.

  2. <!DOCTYPE html>
        <html>
        <head>
        <meta charset="utf-8">
        
        <link href="https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />
        </head>
  3. On the body section include the Editor JS files and define the area for the editor.

  4.     <body>  
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js"></script>
        
        <div class="sample">
        <h2>image upload example.</h2>
        <form>
        <textarea id="edit" name="content"></textarea>
        </form>
        </div>
        
  5. Initialize the editor and set the image upload URL

  6.     <script>
        new FroalaEditor('#edit', {
        // Set the image upload URL.
        imageUploadURL: '/UploadFiles',
        
        imageUploadParams: {
        id: 'my_editor'
        }
        })
        </script>
        </body>
        </html>

The full code should look like this:

<!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <link href="https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />
    </head>
    
    <body>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js"></script>
    
    <div class="sample">
    <h2>image upload example.</h2>
    <form>
    <textarea id="edit" name="content"></textarea>
    </form>
    </div>
    
    
    <script>
    new FroalaEditor('#edit', {
    
    imageUploadURL: '/UploadFiles',
    
    imageUploadParams: {
    id: 'my_editor'
    }
    })
    </script>
    </body>
    </html>

The full code should look like this:

<!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <link href="https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />
    </head>
    
    <body>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js"></script>
    
    <div class="sample">
    <h2>Image upload example.</h2>
    <form>
    <textarea id="edit" name="content"></textarea>
    </form>
    </div>
    
    
    <script>
    new FroalaEditor('#edit', {
    
    imageUploadURL: '/UploadFiles',
    
    imageUploadURL: {
    id: 'my_editor'
    }
    })
    </script>
    </body>
    </html>

Backend

ImageUpload.java servlet handles the upload part. The servlet has basic image format validations that can be easily extended.

The uploads directory must be set to a valid location before making uploads. The path can be any folder that is accessible and writable.

If the uploaded image passes the validation step, the server responds with a JSON object containing a link to the uploaded file.

e.g.: {"link":"http://server_address/upload/name_of_file"}. FileServlet.java manages the GET request to the "/files/" folder.

package com.froala.examples.servlets;
  
  import java.io.File;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.PrintWriter;
  import java.nio.file.Files;
  import java.util.HashMap;
  import java.util.Map;
  import java.util.UUID;
  
  import javax.servlet.ServletException;
  import javax.servlet.annotation.MultipartConfig;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import javax.servlet.http.Part;
  
  import org.apache.commons.io.FilenameUtils;
  import org.apache.commons.lang.ArrayUtils;
  
  import com.google.gson.Gson;
  
  /**
  * Servlet implementation class UploadImage
  */
  @WebServlet(name = "ImageUploadServlet", urlPatterns = {
  "/upload_image"
  })
  
  @MultipartConfig
  public class ImageUpload extends HttpServlet {
  private static final long serialVersionUID = 1L;
  
  /**
  * @see HttpServlet#HttpServlet()
  */
  public ImageUpload() {
  super();
  }
  
  /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  *      response)
  */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  // The route on which the file is saved.
  File uploads = new File("/PATH TO/YOUR PROJECT/WORKSPACE/WEBCONTENT/WEB-INF/SOME FOLDER/");
  String multipartContentType = "multipart/form-data";
  String fieldname = "file";
  Part filePart = request.getPart(fieldname);
  Map < Object, Object > responseData = null;
  
  // Create path components to save the file.
  final PrintWriter writer = response.getWriter();
  
  String linkName = null;
  String name = null;
  
  try {
      // Check content type.
      if (request.getContentType() == null ||
          request.getContentType().toLowerCase().indexOf(multipartContentType) == -1) {
  
          throw new Exception("Invalid contentType. It must be " + multipartContentType);
      }
  
      // Get file Part based on field name and also image extension.
      filePart = request.getPart(fieldname);
      String type = filePart.getContentType();
      type = type.substring(type.lastIndexOf("/") + 1);
  
      // Generate random name.
      String extension = type;
      extension = (extension != null && extension != "") ? "." + extension : extension;
      name = UUID.randomUUID().toString() + extension ;
  
      // Get absolute server path.
      String absoluteServerPath = uploads + name;
  
      // Create link.
      String path = request.getHeader("referer");
      linkName = path + "files/" + name;
  
      // Validate image.
      String mimeType = filePart.getContentType();
      String[] allowedExts = new String[] {
          "gif",
          "jpeg",
          "jpg",
          "png",
          "svg",
          "blob"
      };
      String[] allowedMimeTypes = new String[] {
          "image/gif",
          "image/jpeg",
          "image/pjpeg",
          "image/x-png",
          "image/png",
          "image/svg+xml"
      };
  
      if (!ArrayUtils.contains(allowedExts, FilenameUtils.getExtension(absoluteServerPath)) ||
          !ArrayUtils.contains(allowedMimeTypes, mimeType.toLowerCase())) {
  
          // Delete the uploaded image if it dose not meet the validation.
          File file = new File(uploads + name);
          if (file.exists()) {
              file.delete();
          }
  
          throw new Exception("Image does not meet the validation.");
      }
  
      // Save the file on server.
  
      File file = new File(uploads, name);
  
      try (InputStream input = filePart.getInputStream()) {
          Files.copy(input, file.toPath());
      } catch (Exception e) {
        writer.println("<br/> ERROR: " + e);
      }
  
  } catch (Exception e) {
      e.printStackTrace();
      writer.println("You either did not specify a file to upload or are " +
          "trying to upload a file to a protected or nonexistent " +
          "location.");
      writer.println("<br/> ERROR: " + e.getMessage());
      responseData = new HashMap < Object, Object > ();
      responseData.put("error", e.toString());
  
  } finally {
      // Build response data.
      responseData = new HashMap < Object, Object > ();
      responseData.put("link", linkName);
  
      // Send response data.
      String jsonResponseData = new Gson().toJson(responseData);
      response.setContentType("application/json");
      response.setCharacterEncoding("UTF-8");
      response.getWriter().write(jsonResponseData);
  }
  }
  }

FileServlet.java manages the GET requests that come from the Froala Editor.

The requests come in the following format "http://server_address/files/name_of_file". To serve the resources, the servlet needs to have the same path as ImageUpload.java servlet.

package com.froala.examples.servlets;
  
  import java.io.File;
  import java.io.IOException;
  import java.net.URLDecoder;
  import java.nio.file.Files;
  
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  
  @WebServlet("/files/*")
  public class FileServlet extends HttpServlet {
  
  private static final long serialVersionUID = 1L;
  
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
  {
  String filename = URLDecoder.decode(request.getPathInfo().substring(1), "UTF-8");
  File file = new File("/PATH TO/YOUR PROJECT/WORKSPACE/WEBCONTENT/WEB-INF/SOME FOLDER/", filename);
  response.setHeader("Content-Type", getServletContext().getMimeType(filename));
  response.setHeader("Content-Length", String.valueOf(file.length()));
  response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
  Files.copy(file.toPath(), response.getOutputStream());
  }
  }

Do you think we can improve this article? Let us know.

[class^="wpforms-"]
[class^="wpforms-"]
[bws_google_captcha]
<div class="gglcptch gglcptch_v2"><div id="gglcptch_recaptcha_1346049087" class="gglcptch_recaptcha"></div> <noscript> <div style="width: 302px;"> <div style="width: 302px; height: 422px; position: relative;"> <div style="width: 302px; height: 422px; position: absolute;"> <iframe src="https://www.google.com/recaptcha/api/fallback?k=6Ld6lNoUAAAAAM626LfCOrnkBFJtYZAKESFCjgv_" frameborder="0" scrolling="no" style="width: 302px; height:422px; border-style: none;"></iframe> </div> </div> <div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: #f9f9f9; border: 1px solid #c1c1c1; border-radius: 3px; height: 60px; width: 300px;"> <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px !important; height: 40px !important; border: 1px solid #c1c1c1 !important; margin: 10px 25px !important; padding: 0px !important; resize: none !important;"></textarea> </div> </div> </noscript></div>
[class^="wpforms-"]
[class^="wpforms-"]
[bws_google_captcha]
<div class="gglcptch gglcptch_v2"><div id="gglcptch_recaptcha_116918706" class="gglcptch_recaptcha"></div> <noscript> <div style="width: 302px;"> <div style="width: 302px; height: 422px; position: relative;"> <div style="width: 302px; height: 422px; position: absolute;"> <iframe src="https://www.google.com/recaptcha/api/fallback?k=6Ld6lNoUAAAAAM626LfCOrnkBFJtYZAKESFCjgv_" frameborder="0" scrolling="no" style="width: 302px; height:422px; border-style: none;"></iframe> </div> </div> <div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: #f9f9f9; border: 1px solid #c1c1c1; border-radius: 3px; height: 60px; width: 300px;"> <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px !important; height: 40px !important; border: 1px solid #c1c1c1 !important; margin: 10px 25px !important; padding: 0px !important; resize: none !important;"></textarea> </div> </div> </noscript></div>
[class^="wpforms-"]
[class^="wpforms-"]
[bws_google_captcha]
<div class="gglcptch gglcptch_v2"><div id="gglcptch_recaptcha_1993104970" class="gglcptch_recaptcha"></div> <noscript> <div style="width: 302px;"> <div style="width: 302px; height: 422px; position: relative;"> <div style="width: 302px; height: 422px; position: absolute;"> <iframe src="https://www.google.com/recaptcha/api/fallback?k=6Ld6lNoUAAAAAM626LfCOrnkBFJtYZAKESFCjgv_" frameborder="0" scrolling="no" style="width: 302px; height:422px; border-style: none;"></iframe> </div> </div> <div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: #f9f9f9; border: 1px solid #c1c1c1; border-radius: 3px; height: 60px; width: 300px;"> <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px !important; height: 40px !important; border: 1px solid #c1c1c1 !important; margin: 10px 25px !important; padding: 0px !important; resize: none !important;"></textarea> </div> </div> </noscript></div>