jspelmultipartform-data

How to parse multipart form-data using only EL


Similar to ${param.key}, is there a way to interpret a multipart/form-data encrypted form using EL without Java?

If not possible, is there a workaround to include a file input in a form without using multipart/form-data encryption?


Solution

  • multipart/form-data is used to upload file. This could be big and uploading it could take a while. In order not to block other incoming requests the processing could be asynchronous.

    With Java:

    @MultipartConfig:

    For a servlet receiving multipart/form-data you have to add the @MultipartConfig annotation in front of the servlet, in order to get the values of the plain text parameters by calling request.getParameter("notFileFieldName");. Otherwise the call will return null.

    But with the file and its content, it didn't work this way.
    The file name, content-type, size and content could be retrieved from the Part object returned by
    request.getPart("theFileFieldName");

    For JSP you can add the following snipplet in the web.xml:

    <servlet>
        <servlet-name>UploadFile</servlet-name>
        <jsp-file>/path/form.jsp</jsp-file>
        <multipart-config></multipart-config>
    </servlet>
    <servlet-mapping>
        <servlet-name>UploadFile</servlet-name>
        <url-pattern>/path/form.jsp</url-pattern>
    </servlet-mapping>
    

    Where the line <multipart-config></multipart-config> activate the above behavior for the JSP.
    So ${param.notFileFieldName} will be evaluated to its value.
    But not the ${param.theFileFieldName}

    AsyncContext could used to process the upload

    But you won't a java solution.

    With Javascript: FileReader()

    A basic example how you can read file on the client side. (without upload) Source: https://developer.mozilla.org/de/docs/Web/API/FileReader/readAsDataURL

    HTML

    <input type="file" onchange="previewFile()"><br>
    <img src="" height="200" alt="Image preview...">
    

    JavaScript:

    function previewFile() {
      var preview = document.querySelector('img');
      var file    = document.querySelector('input[type=file]').files[0];
      var reader  = new FileReader();
    
      reader.addEventListener("load", function () {
        preview.src = reader.result;
      }, false);
    
      if (file) {
        reader.readAsDataURL(file);
      }
    }
    

    try it on jsfiddle

    If upload is needed it could be done AJAX.