Search code examples
ajaxwicketckeditor5

Retrieve the multipart data from the request inside a AbstractDefaultAjaxBehavior


I'm trying to create a component to use CKEditor with Apache Wicket. I'm adding a plugin in CKEditor to send an image to the server. For that, I used the example given for the client side:

CKEditor: Custom image upload adapter

For the server side, I created this Java code:

add(new AbstractDefaultAjaxBehavior() {
        @Override
        protected void updateAjaxAttributes(final AjaxRequestAttributes attributes) {
            super.updateAjaxAttributes(attributes);
            attributes.setMethod(Method.POST);
            attributes.setMultipart(true);
            attributes.setDataType("json");
        }

        @Override
        protected void respond(final AjaxRequestTarget target) {

            // Avoid the redirect (302)
            final RequestCycle requestCycle = getRequestCycle();
            requestCycle.scheduleRequestHandlerAfterCurrent(null);

            // Return the picture URL
            final WebResponse response = (WebResponse) RequestCycle.get().getResponse();
            response.setStatus(200);
            response.setContentType("application/json");
            response.write("{ \"url\": \"http://localhost:8080/image/foobar.jpg\"}");
        }

        @Override
        public void renderHead(final Component component, final IHeaderResponse response) {
            super.renderHead(component, response);
            final String callbackUrl = getCallbackUrl().toString();
            response.render(JavaScriptHeaderItem.forScript("ckeditorCallbackUrl = '" + callbackUrl + "';",
                    "ckeditorCallbackUrl"));
        }
    });

But in the respond method, I don't know how to access to the multipart data with the image.

How to retrieve this form-data ?

Thank you.


Solution

  • You can read the files with:

    ServletWebRequest webRequest = (ServletWebRequest) RequestCycle.get().getRequest();
    MultipartServletWebRequest multiPartRequest = webRequest.newMultipartWebRequest(getMaxSize(), "ignored");
    multiPartRequest.parseFileParts();
    Map<String, List<FileItem>> files = multiPartRequest.getFiles();
    

    You can read more about this at http://wicketinaction.com/2012/11/uploading-files-to-wicket-iresource/