Search code examples
springfroala

Froala image loading fails after uploading


I am trying to upload image to the server in Froala editor. However it fails to load uploaded image. The following error is returned from the editor:

http://localhost:8080/create-page/images/22952f64-3b5a-4cf4-8095-0a2fa3198819.jpeg 404 () {code: 1, message: "Image cannot be loaded from the passed link."}

and the response is undefined -> response: undefined

However, this is a correct link and I am able to open the image in my browser when I click on it.

I have the following code for froala editor:

$('.text-editor').froalaEditor({
    /*theme: 'gray',
    zIndex: 2001,*/
    /*theme: 'dark',
    zIndex: 2003,*/
    theme: 'custom',
    charCounterCount: false,
    toolbarButtons: ['bold', 'italic', 'underline', 'strikeThrough', '|', 
'fontFamily', 'fontSize',
        'color', '|', 'align', 'outdent', 'indent', 'insertLink', 
'insertImage', 'embedly',
        '|', 'emoticons     ', 'specialCharacters', 'insertHR', 'selectAll', '|', 'spellChecker', 'undo', 'redo'],
    quickInsertTags: [],
    heightMin: 500,
    imageUploadURL: '/image/upload',
    imageMaxSize: 5 * 1024 * 1024,
    imageUploadMethod: 'POST',
    // Set the load images request URL.
    imageManagerLoadURL: "http://localhost:8080/",

    // Set the load images request type.
    imageManagerLoadMethod: "GET",
    /*imageUploadParams: {id: 'my_editor'}*/
})
.on('froalaEditor.contentChanged', function (e, editor) {
    console.log("Page content changed");

    var pageContent = $(this).find('.fr-view').html();
    var id = $('#pageId').text();

    var pageJson =  {"id": id, "pageContent": pageContent};
    console.log(pageJson);

    $.ajax({
        type: 'POST',
        url: '/page/edit',
        contentType: 'application/json',
        data: JSON.stringify(pageJson),
        dataType: 'json'

    }).done (function(data) {

        //console.log("page " + data.id + " was updated");

    }).fail (function(err) {
        console.error(err);
    });
})
.on('froalaEditor.image.error', function (e, editor, error, response) {
    // Bad link.
    if (error.code == 1) {
        console.log(error);
        console.log("response: " + response);
    }

    // No link in upload response.
    else if (error.code == 2) { 
        console.log(error);
    }

    // Error during image upload.
    else if (error.code == 3) { 
        console.log(error);
    }

    // Parsing response failed.
    else if (error.code == 4) { 
        console.log(error);
        console.log("response: " + response);
    }

    // Image too text-large.
    else if (error.code == 5) {
        console.log(error);
    }

    // Invalid image type.
    else if (error.code == 6) {
        console.log(error);
    }

    // Image can be uploaded only to same domain in IE 8 and IE 9.
    else if (error.code == 7) {
        console.log(error);
    }

    // Response contains the original server response to the request if available.
  });

For the server side I use Java Spring framework and the following code to upload the image:

public ImageLink upload(MultipartFile file, String baseUrl) {

    String linkName = null;
    String type = file.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;

    try {
        file.transferTo(resourceLoader.getResource("/create-page/images/" + name).getFile());

    } catch (Exception e) {
        e.printStackTrace();
    }

    logger.info(baseUrl);

    linkName = "images/" + name;
    ImageLink link = new ImageLink();
    link.setLink(linkName);

    logger.info(link.toString());

    return link;

} 

So, the response body is like this:

{
    "link": "images/97861510-5ca9-4d0d-968c-214ca771832a.png"
}

Froala seems to add http://localhost:8080/create-page to it, so I am returning relative path. I tried different variants, like returning the whole address but it is still not working.

Please point to me what am I doing wrong. Thank you!


Solution

  • It seems like the server wasn't able to upload the image on time, so the froala was making the request while the image was not ready yet. I added Thread.sleep(5000); to the controller before send the response to the client. Not sure if it is a good solution but it solved my issue.