簡單說明需求:
- 利用 .Net 程式將一個 PDF 檔案壓縮, 並將其轉為BASE64字串.
- 呼叫一個 Java 的 Web Service, 將此 BASE64 字串傳送到另一端.
- Java 程式要轉換此 BASE64 字串, 並回存成 PDF 檔案.
這邊省略掉 Web Service 的傳輸說明, 僅說明 .Net 程式的壓縮與轉換 BASE64, 以及 Java 程式的 BASE64 轉換與解壓縮.
- .Net C# 程式:12345678910111213141516171819202122232425
// 讀取 PDF 檔案
byte
[] fileData = File.ReadAllBytes(
@"C:\test.pdf"
);
// 用來儲存最後轉換為 BASE64 字串的變數
string
cmpData =
string
.Empty;
// 將檔案資料轉至 MemoryStream
using
(MemoryStream msIn =
new
MemoryStream(fileData))
{
// 建立輸出的 MemoryStream
using
(MemoryStream msOut =
new
MemoryStream())
{
// 建立 GZipStream, 設定輸出的 MemoryStream, 以及壓縮模式
using
(GZipStream gzIn =
new
GZipStream(msOut, CompressionMode.Compress))
{
byte
[] bytes =
new
byte
[4096];
int
cnt;
// 從 msIn 讀取資料, 透過 gzIn 將資料壓縮後, 輸出至 msOut
while
((cnt = msIn.Read(bytes, 0, bytes.Length)) != 0)
{
gzIn.Write(bytes, 0, cnt);
}
}
// 利用 Convert 將 byte[] 轉為 BASE64 字串
cmpData = Convert.ToBase64String(msOut.ToArray());
}
}
- Java 程式:
以下程式預計用到的 class 如下:
java.util.zip.GZIPInputStream
java.io.FileOutputStream
org.apache.commons.codec.binary.Base641234567891011121314151617// 假設此字串是 .Net 程式傳過來的BASE64字串
String dataString =
"xxxxxxxxxxx"
;
// 1. 利用 Apache Commons Codec 套件中的 Base64 類別轉換 BASE64 字串
// 2. 使用 ByteArrayInputStream 將 byte[] 傳至 Stream 類別
// 3. 利用 GZIPInputStream 處理此壓縮資料
GZIPInputStream gis =
new
GZIPInputStream(
new
ByteArrayInputStream(Base64.decodeBase64(dataString)));
// 建立一個檔案輸出的 FileOutputStream
FileOutputStream fout =
new
FileOutputStream(
"C:\\data.pdf"
);
int
c;
// 將解壓縮的資料輸出至檔案
while
((c = gis.read()) != -
1
) {
fout.write(c);
}
// 關閉 Streams
fout.close();
gis.close();
PS. 有人可能會發現執行GZip後, 資料反而變大了. 原因出在一些資料(EX: PDF)本身就已經有經過壓縮的技術, 再壓縮一次不一定比較好.
沒有留言:
張貼留言