Store a PDF in a mySQL DB using HTML jQuery and Java

I need to store a pdf (each pdf will be < 5 pages maximum) in a mySQL database (yes I know this is not recommended). The column is defined as mediumblob. The test pdf is 198 KB. I get the error “Errors occurred in addMedicalPlan: java.io.FileNotFoundException: " followed by a dump of the file " JVBERi0xLjcKCjQgMCBvYmoKKElkZW50aXR5KQplbmRvYmoKNS …” and at the end “(The filename or extension is too long)”.

I have managed to do this with images and have been trying to re-purpose that code to store the pdf; by researching articles and other questions. Unfortunately, for me, most of the example relate to PHP. I have been able to read the pdf and display it in the page with this code:

HTML:

<div class="form-group">
    <embed width="191" height="207" id="image" src="" type="application/pdf">
    <input class="form-control-file col-lg-12 col-md-12 col-sm-12 col-xs-12 photo-input" type="file" id="photo" name="photo" placeholder="PDF">
</div>

jQuery:

$(document).on( 'change' , '.photo-input' , function(){
//Check for a valid image extension
var img1 = this .files[ 0 ].type;
alert( "img1: " + img1);
var mySubString = img1.substring(
img1.lastIndexOf( "image" ) + 13
);
alert( "mySubString: " + mySubString)
if ($.inArray(mySubString, [ 'pdf' ]) == - 1 ) {
alert( 'Add invalid extension 1!' );
$( '#image' ).attr( 'src' , '' );
} else {
//Check for a valid image size
if ( this .files[ 0 ].size < 10000000 ){
readURL( this , this .id);
} else {
alert( "This image is to large (must be < 1 MB)." )
$( '#image' ).attr( 'src' , '' );
}
var img1 = document.getElementById( 'image' );
img2 = (img1.getAttribute( 'src' )).replace(/^data:application\/(pdf);base64,/, "" );
}
});

function readURL(input, id) {
if (input.files && input.files[ 0 ]) {
var reader = new FileReader();
reader.onload = function (e) {
$( '#image' ).attr( 'src' , e.target.result);
}
reader.readAsDataURL(input.files[ 0 ]);
}
}

Do I need to strip off “data:application/(pdf);base64”, i.e., img2 = (img1.getAttribute(‘src’)).replace(/^data:application/(pdf);base64,/, “”); for the pdf? I do similar for storing my images (i.e., img2 = (img1.getAttribute(‘src’)).replace(/^data:image/(png|jpg|jpeg|gif);base64,/, “”);). Is this superfluous for pdf files?

I then pass the pdf to be stored with ajax:

$.ajax({
type: "POST" ,
url: "MedicalPlanAddView" ,
cache: false ,
data : {
ssAccountLevel : sessionStorage.getItem( 'ssAccountLevel' ),
ssAccountID : sessionStorage.getItem( 'ssAccountID' ),
ssNameID : sessionStorage.getItem( 'ssNameID' ),
image : img2,
mpNameAdd: $( "#mpNameAdd" ).val(),
},
})

And the server side java is:

private static byte [] getByteArrayFromFile( final String handledDocument) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final InputStream in = new FileInputStream(handledDocument);
final byte [] buffer = new byte [ 500 ];
int read = - 1 ;
while ((read = in.read(buffer)) > 0 ) {
baos.write(buffer, 0 , read);
}
in.close();
return baos.toByteArray();
}
ps.setString( 1 , nameId);
ps.setString( 2 , medicalPlanName);
ByteArrayInputStream bais = new
ByteArrayInputStream(getByteArrayFromFile(medicalPlan)); //pdf image
ps.setBlob( 3 , bais);
ps.setString( 4 , updateDate);
ps.executeUpdate();

I am not a programmer and am doing this pro-bono and learning as I go for my organisation.

Kind regards,

Glyn

I don’t have much JS knowledge, but it seems to me that the error message relates to the filename rather than the contents of the file. In my limited knowledge, I can’t see why there would be any difference in handling PDFs from handling images - they’re both binary data streams. I also can’t see how the variable names you use in the server-side Java relate to the data names you submit from the Ajax code, but again that might lack of knowledge on my part.

Hi droopsnoot,

You are correct in the assumption that there should be no difference (well very little) in dealing with images vs pdf. That is why I started with my code for handling images. So I went back to the original code for handling images and made incremental changes to deal with pdf and managed to get it working. The final code is:

HTML:

<div class="form-group">
        <embed width="191" height="207" id="image" src="" type="application/pdf" class="img-thumbnail">
        <input class="form-control-file col-lg-12 col-md-12 col-sm-12 col-xs-12 photo-input" type="file" id="photo" name="photo" placeholder="PDF">
</div>

jQuery:

$(document).on('change', '.photo-input', function(){
    //Check for a valid image extension
    var img1 = this.files[0].type;
    var mySubString = img1.substring(
        img1.lastIndexOf("image") + 13
    );
        if($.inArray(mySubString, ['pdf']) == -1) {
        alert('invalid extension!');
        $('#image').attr('src', 'data:application\/(pdf);base64');
    }else{
        //Check for a valid image size
        if (this.files[0].size < 10000000){
            readURL(this, this.id);
        }else{
            alert("This image is to large (must be < 1 MB).")
            $('#image').attr('src', 'data:application\/(pdf);base64');
        }
        var img1 = document.getElementById('image');
        img2 = (img1.getAttribute('src')).replace(/^data:application\/(pdf);base64,/, "");
    }
});

function readURL(input, id) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#image').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

    submitHandler : function(showMPAddForm) {
        var img1 = document.getElementById('image');
        img2 = (img1.getAttribute('src')).replace(/^data:application\/(pdf);base64,/, "");

        $.ajax({
            type: "POST",
            url: "MedicalPlanAddView",
            cache: false,
            data : {
                ssAccountLevel : sessionStorage.getItem('ssAccountLevel'),
                ssAccountID : sessionStorage.getItem('ssAccountID'),
                ssNameID : sessionStorage.getItem('ssNameID'),

                image : img2,
                mpNameAdd: $("#mpNameAdd").val(),
            }, 
        })
        .fail (function(jqXHR, textStatus, errorThrown) {
            //alert(jqXHR.responseText);
            $('#ajaxGetUserServletResponse13').text('Error adding Medical Plan.');
        })
        .done(function(responseJson){
            $('#ajaxGetUserServletResponse13').text('Medical Plan added.');
            showActionPlanDataTable();
        })
    }

SQL:

                ps = c.prepareStatement(updateWithPhoto);
                ps.setString(1, medicalPlanName);

                BASE64Decoder decoder = new BASE64Decoder();
                byte[] imageByte = decoder.decodeBuffer(medicalPlan);
                ps.setBlob(2, new SerialBlob(imageByte));

                ps.setString(3, updateDate);
                ps.setString(4, medicalPlanId);

                ps.executeUpdate();

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.