Reputation: 2195
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 && 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
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