简体   繁体   English

使用javascript上传文件并设置为jsf bean属性

[英]upload the file with javascript and set into the jsf bean property

I upload the files with javascript as following. 我使用javascript上传文件,如下所示。

<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//... 数据:图像/ PNG; BASE64,iVBORw0KGgoAAAANSUhEUgAAAk8AAAD2CAIAAABA // ...

I used the readAsDataURL javascript method to show the image. 我使用了readAsDataURL javascript方法来显示图像。 I would like to convert the result into byte Array. 我想将结果转换为字节数组。 Is there any way to convert the byte Array? 有什么办法可以转换字节数组吗?

Let's supose you received the result in the server side (using the variable result ). 假设您在服务器端收到了结果(使用变量result )。

First you need to remove the Data URI prefix: 首先,您需要删除数据URI前缀:

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

Then convert the base64 to byte[] using javax.xml.bind.DatatypeConverter : 然后使用javax.xml.bind.DatatypeConverter将base64转换为byte []:

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: 可选地 ,您可以根据需要在客户端删除Data URI前缀,而不是在服务器端删除它(第一步),方法是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM