2013-08-06 52 views
1

我正在使用AJAX將base64編碼後的圖像從我的JSP發送到servlet。在servlet方面,我試圖解碼並將其保存到文件或呈現給瀏覽器。 我得到一個空的圖像。這裏是我的servlet端代碼JAVA編碼/解碼基礎64並在瀏覽器中呈現或將其保存到文件

String imageStr = request.getParameter("image"); 
byte[] decoded = Base64.decodeBase64(imageStr); 

    String path = "D:\\myImage.png"; 
    try { 
    OutputStream out1 = new BufferedOutputStream(new FileOutputStream(path)); 
     out1.write(decoded); 
    } finally { 


    } 

我得到一個圖像,但它的空。

+0

你確定你確定'image'不是空的?也許你應該看看MultiPart,例如。 http://stackoverflow.com/questions/9269997/file-or-image-uploading-using-java-servlet-with-apache-commons-library –

+0

我打印圖像字符串,我看到所有瘋狂的人物。 – Raghu

回答

2

嘗試關閉流,應該刷新所有緩存的數據:

String imageStr = request.getParameter("image"); 
byte[] decoded = Base64.decodeBase64(imageStr); 

String path = "D:\\myImage.png"; 
OutputStream out1 = null; 

try { 
    out1 = new BufferedOutputStream(new FileOutputStream(path)); 
    out1.write(decoded);    
} finally { 
    if (out1 != null) { 
     *out1.close();* 
    } 
} 

,並確保decoded陣列確實包含了一些數據。

+0

如果try塊中出現錯誤(例如'out1.write()'exceptioning),您應該總是關閉finally塊中的資源(也就是將close行降低兩行)。 – supersam654

+0

對,更新示例 –

+0

這種幫助。我得到一個5 kb的圖像,但在假想圖像的中心只有一個紅色的X. – Raghu

相關問題