使用JavaScript和JSF的图像上传偶尔不起作用

Image Upload with JavaScript and JSF does sporadically not work

本文关键字:偶尔 不起作用 图像 JavaScript JSF 使用      更新时间:2023-09-26

我在JavaScript和JSF中上传图像时遇到问题:

在移动网页上,用户可以使用集成相机拍照,该相机会立即上传到服务器并存储在MySql数据库中,但有时上传会停止。当这个问题发生时,我看不出有什么规律。它在大多数情况下都有效。

这里的代码:

JSF

<h:form id="imageInputForm">
  <h:panelGroup styleClass="invisible">
    <input type="file" id="files" name="files[]"  accept="image/*;capture=camera" />
    <h:inputHidden value="#{bean.imageData}" type="text" id="inputId" />
  </h:panelGroup>
  <div id="loading" style="display:none; position:absolute; z-index: 5000; margin: 0 auto; width:100%"  >
    <table style="width:100%; height:100%; align:center; text-align:center;">
        <tr>
          <td>
             <img height="130px" width="130px;" src="../../resources/ajaxloading.gif" alt="" />
          </td>
        </tr>
    </table>
  </div>    
</h:form>
<h:form>
   <p:commandLink immediate="true" onclick="onClickTakeCam();">
      <p:graphicImage height="27" width="35" value="/resources/camera_icon.png" style="border: none;" />
  </p:commandLink>
</h:form>   
<style type="text/css">  
    .invisible {
        display:none;
    }
</style>
<script>
    function onClickTakeCam() { 
        $("#files").click();
    }
    function handleFileSelect(evt) {
        $('#loading').show();
        var files = evt.target.files; // FileList object
            for (var i = 0, f; f = files[i]; i++) {
                  if (!f.type.match('image.*')) {
                    continue;
                  }
                 var reader = new FileReader();
                reader.onload = (function(theFile) {
                    return function(e) {
                      var result = e.target.result;
                      var input = document.getElementById("imageInputForm:inputId");
                      input.value = result;
                      document.getElementById('imageInputForm').submit();
                    };
                  })(f);
               reader.readAsDataURL(f); 
            }
        }
        document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

Bean

public String getImageData() {
    return imageData;
}

public void setImageData(String imageData) {
    if (imageData != null && !imageData.equals(this.getImageData())) {
        this.imageData = imageData;
        imageUploaded();
    } else {
        this.imageData = imageData;
    }
}
public void imageUploaded() {
   byte [] uploadedImage = Base64.decodeBase64(this.getImageData().substring(22));
    //process byte array from here
    //[...]
}

我在您的代码中看到两个问题。

第一个原因是,当您使用FileReader读取文件时,并没有处理错误。您应该设置属性FileReader.oneror和FileReader.onabort。否则,当发生错误或文件读取中止时,不会发生任何事情,看起来页面已经冻结。

第二个问题是以下线路:

<p:commandLink immediate="true" onclick="onClickTakeCam();">

您最好添加return false;或使用onstart。否则Primefaces会发送一些AJAX请求,这些请求可能会与随后的表单提交混合在一起。

如果修复上述问题并不能解决冻结问题,请提供更多详细信息,说明挂起的内容和执行的内容(例如,请求是否发送到服务器)。