1. 程式人生 > >BASE64Decoder 對檔案編碼解碼

BASE64Decoder 對檔案編碼解碼

本文以圖片示例

1.對圖片進行編碼

	BASE64Encoder encoder = new BASE64Encoder();
String rootpath = request.getSession().getServletContext()
						.getRealPath("/").replace("\\", "/")
						+ "../upload/CheckInfo/" + type + "/";
				StringBuilder pictureBuffer = new StringBuilder();
				rootpath += fileNames[i];
				InputStream input = new FileInputStream(new File(rootpath));
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				byte[] temp = new byte[1024];
				for (int len = input.read(temp); len != -1; len = input
						.read(temp)) {
					out.write(temp, 0, len);
					pictureBuffer.append(encoder.encode(out.toByteArray()));
					// out(pictureBuffer.toString());
					out.reset();
				}

這裡得到   pictureBuffer.toString()  就是最後的編碼結果 ,前端支援直接編碼顯示圖片

2.對base64編碼進行解碼 生成圖片

BASE64Decoder decoder = new BASE64Decoder();
			String rootpath = request.getSession().getServletContext()
					.getRealPath("/").replace("\\", "/")
					+ "../" + data.get(i).getfSavePath();
			File temp= new File(rootpath);
			if (!temp.exists()) {
				FileOutputStream write = new FileOutputStream(new File(rootpath));
				byte[] decoderBytes = decoder.decodeBuffer(data.get(i).getfBase64Code());
				write.write(decoderBytes);
				write.close();
			}

  生成圖片的路徑就是 rootpath