Days
Hours
Minutes
Seconds
x

New Advanced File Management – Learn More

Skip to content

Java File Validation

How it works

  1. Upload file to the server.
  2. Validate file on the server side before storing it.

Jump to Complete Example

File Upload

The Server Upload section describes the steps to upload a file to a server. You can validate files when you insert them in the editor, however that only checks the filename and not the mime type. It is advisable to make additional checks on the server side to make sure users only upload valid file formats.

Validate Extension

The editor's Java SDK can check the file extension before storing it on disk, and it also checks the mime type.

ImageOptions options = new ImageOptions();
options.setFieldname("myFile");
options.setValidation(new ImageValidation(new String[] { "txt", "pdf", "doc" }, new String[] { "text/plain", "application/msword", "application/x-pdf", "application/pdf" }));

Map<Object, Object> responseData = Image.upload(request, fileRoute, options);

Custom Validation

You can also pass a custom method instead of validating the extension and mime type. This gives you full control on what types of files you want to store on disk. Below is an example of how to validate if a file is smaller than 10Mb.

FileOptions options = new FileOptions();
options.setFieldname("myFile");
options.setValidation(new FileValidation(new CustomValidation() {

    @Override
    public boolean validate(String filePath, String mimeType) {

        java.io.File f = new java.io.File(filePath);
        long size = f.length();

        if (size > 10 * 1024 * 1024) {
            return false;
        }
        return true;
    }
}));
Map<Object, Object> responseData = File.upload(request, fileRoute, options);

Complete Example

<script>
  new FroalaEditor('.selector', {
    // Set the file upload URL.
    fileUploadURL: '/upload_file_validation',

    fileUploadParams: {
      id: 'my_editor'
    }
  })
</script>
package com.froala.examples.servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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 com.froala.editor.CustomValidation;
import com.froala.editor.File;
import com.froala.editor.file.FileOptions;
import com.froala.editor.file.FileValidation;
import com.google.gson.Gson;

/**
 * Servlet implementation class UploadFileValidation
 */
@WebServlet("/upload_file_validation")
@MultipartConfig
public class UploadFileValidation extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadFileValidation() {
        super();

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String fileRoute = "/public/";

        FileOptions options = new FileOptions();
        options.setFieldname("myFile");
        options.setValidation(new FileValidation(new CustomValidation() {

            @Override
            public boolean validate(String filePath, String mimeType) {

                java.io.File f = new java.io.File(filePath);
                long size = f.length();

                if (size > 10 * 1024 * 1024) {
                    return false;
                }
                return true;
            }
        }));

        Map<Object, Object> responseData;
        try {
            responseData = File.upload(request, fileRoute, options);
        } catch (Exception e) {
            e.printStackTrace();
            responseData = new HashMap<Object, Object>();
            responseData.put("error", e.toString());
        }
        String jsonResponseData = new Gson().toJson(responseData);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(jsonResponseData);
    }

}

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