使用JSF上传两个文件会导致同一文件的两倍

时间:2015-01-19 15:26:46

标签: jsf file-upload

我有一个JSF页面+ Bean来上传文件并预览结果(它是图像的)。在bean中,upload方法将数据(base64)放入列表中,JSF页面循环遍历列表以显示图像。

到目前为止,它对第一张图像的效果如预期。但是当我上传第二张图片时,有两件事可能会出错:

  • 第一张图片再次上传
  • 或者,代码稍有变化后,第二张图片根本无法上传,直到我再次重新选择文件并上传。

JSF页面

<h:form enctype="multipart/form-data" id="uploadForm" prependId="false">

    <!-- here I loop through the list to preview the images -->
    <c:forEach var="image" items="#{bean.imageList}">
        <h:graphicImage value="#{image}" />
    </c:forEach>

    <!-- that's the upload -->
    <h:inputFile id="file" value="#{bean.uploadedFile}" />
    <h:commandButton value="submit" action="#{bean.uploadFile}" />
</h:form>

private Part uploadedFile;                // the Part with the uploaded file
private ArrayList<String> imageList;      // the list of images (base64 encoded)

public void uploadFile() throws IOException{
    if(null != uploadedFile){
        String imageType = "data:" + uploadedFile.getContentType() + ";base64,";    // will be something like: "data:image/png;base64,"
        InputStream inputStream = uploadedFile.getInputStream();  // getting the inputStream from the Part
        byte[] imageData;                  // array to but the image data
        try(BufferedInputStream bis = new BufferedInputStream(inputStream)){          // converting the inputStream to a buffered one
            imageData = new byte[bis.available()];        // initializing the byte array with the right size
            bis.read(imageData);           // reading / writing the image data

            // HERE: if I comment out the next line, the second upload will upload the first image again.
            // but if I set the Part to null, the second upload will result in nothing (page reloads, no data uploaded) and I have to upload it again
            uploadedFile = null;
        }
        imageList.add(imageType + javax.xml.bind.DatatypeConverter.printBase64Binary(imageData));    // this adds the base64 image string to the list of images
    }
}

我的bean是@ViewScoped(我需要它来做其他事情)。

所以我的猜测是Part uploadedFile只是没有获得第二个文件的新图像数据,但正如我所说,当它设置为null时,它只是跳过第二个上传处理。

有人看到我做错了吗?

1 个答案:

答案 0 :(得分:2)

您可以尝试以下操作。

    byte[] imageData = new byte[uploadedFile.getSize()];
    try (BufferedInputStream bis = new BufferedInputStream(inputStream)) {
        bis.read(imageData);
        uploadedFile.delete();
    }
  • 使用Part.getSize()
  • 不依赖于available(),不能保证所有可用
  • 使用delete()清除bean

(我自己没试过。)