Froala Editor 3 is here!

Java

Video Upload

The following code example illustrates how to handle video upload on your server using Java as a server-side language. For step by step explanation of the upload flow see video upload concept.

Dependencies

The java video upload example needs the following dependencies:

Frontend

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

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">

  <!-- Include Editor style. -->
  <link href="https://cdn.jsdelivr.net/npm/froala-editor@3.0.0-beta.1/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <div class="sample">
    <h2>Video upload example.</h2>
    <form>
      <textarea id="edit" name="content"></textarea>
    </form>
  </div>

  <!-- Include Editor JS files. -->
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/froala-editor@3.0.0-beta.1//js/froala_editor.pkgd.min.js"></script>

  <!-- Initialize the editor. -->
  <script>
    new FroalaEditor('#edit', {

      // Set the video upload URL.
      videoUploadURL: '/upload_video',
      videoUploadParams: {
        id: 'my_editor'
      }
    })
  </script>
</body>
</html>

Backend

VideoUpload.java servlet will do the upload part. The servlet has basic file format validations this can be easily extended.

The uploads directory must be set to a valid location before any uploads are made. The path can be any folder that is accessible and write available.

After processing the uploaded video, if it passes the validation, the server will respond with a JSON object containing a link to the uploaded file.

E.g.: {"link":"http://server_address/files/name_of_file"}, the FileServlet.java will manage the GET request to "/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 UploadFile
*/
@WebServlet(name = "VideoUploadServlet", urlPatterns = {
   "/upload_video"
})

@MultipartConfig
public class VideoUpload extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public VideoUpload(){
      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);

       // Create path components to save the file.
       Map < Object, Object > responseData;
       final PrintWriter writer = response.getWriter();
       String linkName = 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 file extension.
           String type = filePart.getContentType();
           type = type.substring(type.lastIndexOf("/") + 1);

           // Generate random name.
           String extension = type;
           extension = (extension != null && extension != "") ? "." + extension : extension;
           String 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 file.
           String mimeType = filePart.getContentType();
           String[] allowedExts = new String[] {
               "mp4",
               "webm",
               "ogg"
           };
           String[] allowedMimeTypes = new String[] {
               "video/mp4",
               "video/webm",
               "video/ogg"
           };

           if (!ArrayUtils.contains(allowedExts, FilenameUtils.getExtension(absoluteServerPath)) ||
               !ArrayUtils.contains(allowedMimeTypes, mimeType.toLowerCase())) {

               // Delete the uploaded file.
               File file = new File(absoluteServerPath);

               if (file.exists()) {
                   file.delete();
               }

               throw new Exception("File 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 {
           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 will manage the get requests that come from the Froala Editor.

The requests will come in the following format "http://server_address/files/name_of_file". The servlet needs to have the same path as VideoUpload.java servlet so it can serve the resources.

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());
    }
}