天天看點

旺旺 QQ的聊天記錄(含圖檔)儲存到自己的伺服器

其實這個功能的總思路是 包所有的QQ聊天記錄和旺旺的聊天記錄先拷貝到word,讓word把圖檔進行base64的加密,切記word儲存時候的格式是mht的

比如我儲存了一份聊天記錄,用notepad++打開

可以看到在<!--StartFragment-->

          <!--EndFragment-->标簽内容才是你拷貝的内容圖檔後面的src是content-Location後面的字元

後面我們就是解析了

public String newAddServeRecord() {
		InputStreamReader r = null;
		BufferedReader br = null;
		try {
			String uploadPath = Tools.getStrutsProp().getValue("uploadPath")
					+ "recordImgs/";
			File recf = new File(uploadPath);
			recf.mkdirs();
			String urlPath = Tools.getStrutsProp().getValue("urlPath")
					+ "recordImgs/";

			r = new InputStreamReader(new FileInputStream(mhtFile), "UTF-8");
			br = new BufferedReader(r);
			
			String result = "";
			Map<String, String> imgMap = new HashMap<String, String>();
			
			String startFragment = "<!--StartFragment-->";
			String endFragment = "<!--EndFragment-->";
			String base64 = "Content-Transfer-Encoding: base64";
			String location = "Content-Location: ";

			String str = null;
			while ((str = br.readLine()) != null) {
				if (str.indexOf(startFragment) != -1) {

					if (str.indexOf(endFragment) != -1) {
						result += str.substring(str.indexOf(startFragment)
								+ startFragment.length(),
								str.indexOf(endFragment));
					} else {
						result += str.substring(str.indexOf(startFragment)
								+ startFragment.length(), str.length());
					}
				}

				if (str.indexOf(endFragment) != -1) {
					result += str.substring(0, str.indexOf(endFragment));
				}

				if (str.indexOf(base64) != -1) {
					String locationPath = br.readLine();
					locationPath = locationPath.replace(location, "");

					br.readLine();
					String base64Img = br.readLine();
					imgMap.put(locationPath, base64Img);
				}

			}

			result = result.replaceAll("=20", " ").replaceAll("=3D", "=")
					.replaceAll("<IMG", "<img");

			for (String key : imgMap.keySet()) {
				byte[] imgByte = Base64.decode(imgMap.get(key));

				String fileName = Tools.getDateToSEC() + Tools.getThree()
						+ key.substring(key.lastIndexOf("."));

				FileOutputStream imgOut = new FileOutputStream(uploadPath
						+ fileName);
				imgOut.write(imgByte);
				imgOut.close();
				result = result.replace(key, urlPath + fileName);
			}
			
			// 寫入資料庫
			ServeRecord sr = new ServeRecord();
			sr.setDate(new Date());
			sr.setContent(result);
			sr.setServeCustomer(((Admin) getSession().get(Constant.ADMIN))
					.getName());
			sr.setCustomerId(customer.getId() + "");
			serveRecordDao.insert(sr);
			state = "okrecord";
		} catch (Exception e) {
			logger.error("CustomerManagerAction.newAddServeRecord", e);
			return ERROR;
		} finally {
			try {
				if (null != br) {
					br.close();
				}
				if (null != r) {
					r.close();
				}
			} catch (IOException e) {
				logger.error(
						"CustomerManagerAction.newAddServeRecord[close] error!",
						e);
				return ERROR;
			}
		}
		return SUCCESS;
	}