0

Im trying to convert a fileupload form data to base64. An ajax post sends the form data to backend.

$( "#profileModalForm" ).submit(function( event ) {
    var formData = new FormData(this);
    $.ajax({
        cache: false,
        url: 'SaveProfilePopupData.ws',
        type: "POST",
        enctype: 'multipart/form-data',
        data: formData,        
        contentType: false,
        processData: false,
        success: function (html) {
            $('#notificationArea').html(html);
        }
    });
    event.preventDefault();
});

Then in java side im trying to read the image using apache commons fileupload and save to base64 string.

            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iterator = upload.getItemIterator(request);
            while(iterator.hasNext()){
                FileItemStream item = iterator.next();
                InputStream stream = item.openStream();
                if(!item.isFormField()){
                    byte[] str = new byte[stream.available()];
                    stream.read(str);
                    imageBase64String = new String(Base64.getEncoder().encode(str));

                }
            }

I am only able to get a partial base64 string value of the image i am uploading(In a 7KB image, i can only see a half of the image). What am I doing wrong?

  • 1. You're using base64 - something you more than likely don't need to use. 2. `byte[] str = new byte[stream.available()];` you're only processing what is immediately available; what if there's more to come? – UKMonkey Jun 11 '18 at 13:29
  • related: https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – UKMonkey Jun 11 '18 at 13:30

0 Answers0