使用HTML jQuery和Java将PDF存储在mySQL DB中

时间:2018-11-18 04:24:19

标签: java jquery mysql ajax pdf

我需要在MySQL数据库中存储一个pdf(每个pdf最多<5页)。该列定义为中度。测试pdf为198 KB。我收到错误“在addMedicalPlan中发生错误:java.io.FileNotFoundException:”,然后转储文件“ JVBERi0xLjcKCjQgMCBvYmoKKElkZW50aXR5KQplbmRvYmoKNS ......”,最后是“(文件名或扩展名太长)”。 / p>

我设法用图像做到这一点,并一直试图重新利用该代码来存储pdf;通过研究有关Stackoverflow的文章和其他问题。不幸的是,对我而言,大多数示例都与PHP有关。我已经能够阅读pdf并将其显示在页面中,并显示以下代码:

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]);
    }
}

然后我将pdf通过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(),
  }, 
})

服务器端的Java是:

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();

1 个答案:

答案 0 :(得分:0)

这就是我最终要做的。

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();