JAVA对base 64进行编码/解码,并在浏览器上进行渲染或将其保存到文件中

JAVA对base 64进行编码/解码,并在浏览器上进行渲染或将其保存到文件中,java,image,base64,decode,encode,Java,Image,Base64,Decode,Encode,我使用AJAX将base64编码后的图像从JSP发送到servlet。在servlet端,我尝试解码并将其保存到文件或渲染到浏览器。 我得到一个空的图像。这是我的servlet端代码 String imageStr = request.getParameter("image"); byte[] decoded = Base64.decodeBase64(imageStr); String path = "D:\\myImage.png"; try { OutputStr

我使用AJAX将base64编码后的图像从JSP发送到servlet。在servlet端,我尝试解码并将其保存到文件或渲染到浏览器。 我得到一个空的图像。这是我的servlet端代码

 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 {


    }

我得到一张图片,但它是空的

尝试关闭流,它将刷新所有缓冲数据:

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();*
    }
}

并确保解码的
数组确实包含一些数据。

您确定
图像
不是空的吗?也许你应该看看MultiPart,例如,我打印了图像字符串,看到了所有疯狂的字符。如果try块出现错误(例如
out1.write()
例外),你应该总是关闭finally块中的资源(也就是:将
close
行移低两行)。这种方法很有帮助。我得到一个5 kb的图像,但在假设图像的中心只有一个红色的X。在这种情况下,图像URL可能是错误的,或者服务器没有返回它。现在似乎是另一个问题了。