user1156041
user1156041

Reputation: 2195

upload the file with javascript and set into the jsf bean property

I upload the files with javascript as following.

<h:form id="form1">
    <h:inputHidden binding="#{myBean.inputHidden}" value="#{myBean.fileData}" id="hidden2"/>
        <h3>Second way</h3>
        <input id="upload" type="file" onchange="imageChange(this)"/>
        <img src="#" height="150" id="image" />
        <h:commandButton value="submit" action="#{myBean.save()}"/>
    </h:form>
    <script>
    function readPicture(input, output) {
        alert("Helo ");
        if (input.files &amp;&amp; input.files[0]) {

            var reader = new FileReader();
            reader.onload = function(e)
            {               
                output.attr('src', e.target.result);
                alert(e.target.result);
                document.getElementById('form1:hidden2').value = e.target.result;
            };
            reader.readAsDataURL(input.files[0]);
            //reader.readAsArrayBuffer(input.files[0]);
        }
    }
    function imageChange(input) {
        alert("Helo " + input);
        var img = $("#image");
        readPicture(input, img);
    };


</script>

and I got the result like that

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAk8AAAD2CAIAAABA//...

I used the readAsDataURL javascript method to show the image. I would like to convert the result into byte Array. Is there any way to convert the byte Array?

Upvotes: 0

Views: 1055

Answers (1)

Italo Borssatto
Italo Borssatto

Reputation: 15689

Let's supose you received the result in the server side (using the variable result).

First you need to remove the Data URI prefix:

result = result.substring(result.indexOf(','));

Then convert the base64 to byte[] using javax.xml.bind.DatatypeConverter:

byte[] buf = DatatypeConverter.parseBase64Binary(result);

Optionaly, you can remove the Data URI prefix in the client side if you want, instead of removing it in the server side (first step), by doing:

var result = reader.result.slice(reader.result.indexOf(',') + 1);

Upvotes: 1

Related Questions