我有一个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
时,它只是跳过第二个上传处理。
有人看到我做错了吗?
答案 0 :(得分:2)
您可以尝试以下操作。
byte[] imageData = new byte[uploadedFile.getSize()];
try (BufferedInputStream bis = new BufferedInputStream(inputStream)) {
bis.read(imageData);
uploadedFile.delete();
}
Part.getSize()
available()
,不能保证所有可用delete()
清除bean (我自己没试过。)