您的問題可以分爲以下幾個子步驟:
- 創建從
BufferedImage
所持有其數據的字節數組;
- 對數據進行正確編碼,以便在將其作爲字符串發送到服務器時不會被損壞/修改,例如使用Apache Commons Base64 codec;
- 通過Applet-to-JavaScript通信將數據保存爲隱藏的表單域;
- 通過例如觸發
<h:commandButton>
的onclick
向服務器發送POST請求;
- 以標準JSF方式將編碼的字符串寫入java bean屬性;
- 解碼字符串以獲取表示圖像的字節數組;
- 從字節數組中重新創建圖像並將其注入到視圖作用域bean中。
這就是說,讓我們繼續執行該議程。
在你的applet中,你將有一個方法將做點(1) - (4)。說它是在通常的方式,你獲得的圖像後:
的Java Applet的方法:
public void processImage() throws IOException, JSException {
BufferedImage image = createBufferedImage();//the way you get the image
/* point 1 */
ByteArrayOutputStream bs = new ByteArrayOutputStream();
ImageIO.write(image, "png", bs);
bs.flush();
byte[] imageByteArray = bs.toByteArray();
bs.close();
/* point 1 */
String imageAsString = Base64.encodeBase64String(imageByteArray);//point 2
/* points 3-4 */
JSObject window = JSObject.getWindow(this);
window.call("writeImageValue", new Object[] {imageAsString});
/* points 3-4 */
}
JSF頁面(表單和JavaScript):
<script>
function writeImageValue(imageValue) {
document.getElementById('image').value = imageValue;//point 3
document.getElementById('image-form:submit').click();//point 4
}
</script>
<h:form id="image-form">
<input type="hidden" id="image" name="image" />
<h:commandButton id="submit" action="#{imageSubmitBean.submitImage}" style="display:none" />
</h:form>
JSF管理的bean:
@ManagedBean
@RequestScoped
public class ImageSubmitBean {
@ManagedProperty("#{param.image}")//point 5
private String imageAsString;//getter+setter
@ManagedProperty("#{userBean}")//your view scoped bean
private UserBean userBean;//getter+setter
public String submitImage() throws IOException {
byte[] imageByteArray = Base64.decodeBase64(imageAsString);//point 6
/* point 7 */
InputStream is = new ByteArrayInputStream(imageByteArray);
BufferedImage image = ImageIO.read(is);
is.close();
userBean.setUserImage(image);//update your view scoped bean
/* point 7 */
return null;
}
}
您是否設法使解決方案正常工作? – skuntsel