如何用jQuery將輔助資訊合并到二進位檔案裡一起上傳到WCF
在上傳檔案的時候,往往需要傳遞目前使用者的一些其它的輔助資訊,在此提供一個將這些輔助資訊合并入二進位檔案中一起上傳的方法。
下面代碼將選中檔案上傳的同時,將傳送會話Id、檔案尾碼、檔案類型三個參數。
整個合并後的二進位流分成三部分,如。第一段用1個位元組表示輔助資訊的長度,當然,若第二段比較長,則可以用雙位元組來表示;第二段是輔助資訊,這裡用json格式的字串轉換成ASCII碼數組來表示;第三段為選中檔案的實際內容。
頁面及JavaScript代碼如下:
// 使用POST方式提交伺服器function SendFileToServer(filename, filecontent) { $.ajax({ type: "POST", url: "PictureService.svc/SendIdCardPicture", dataType: 'application/json; charset=utf-8', cache: false, processData: false, data: filecontent, success: function (data) { console.log(data); } });}// File控制項選擇一個檔案時觸發change後的函數$('#File').change(function (evt) { // 介面中有type=file的input控制項 if (evt.target.files.length > 0) { // 遍曆所有type=file的input控制項 for (var i = 0; i < this.files.length; i++) { var file = this.files[i]; var reader = new window.FileReader(); // 定義執行下面reader.readAsArrayBuffer後觸發的load事件的處理函數 reader.onload = function (rResult) { // 組建檔案名 var filename = GetGUID(); // 設定一起傳遞的輔助資訊,這裡包含sessionId、 imageType、fileExtName三項資料 var obj = {}; obj.sessionId = $("#sessionId").val(); obj.imageType = 1; obj.fileExtName = "png"; var jsonShop = $.toJSON(obj); // 把字串轉換成由字元ASCII碼組成的數組 var arr = Array.prototype.map.call(jsonShop, function (c) { return c.charCodeAt(0); }); // 在上述數組前面加入1個字元長度的資料,用以表示數組長度 arr.unshift(arr.length); // 建立一個全新的ArrayBuffer,長度為上述數組長度+檔案長度 var buffer = new ArrayBuffer(rResult.target.result.byteLength + arr.length); // 產生視圖,因為只有在視圖裡才能讀取和插入資料 var dataview = new DataView(buffer); // 把數組推入視圖 for (var i = 0; i < arr.length; i++) { dataview.setUint8(i, arr[i]); } // 因為rResult.target.result是ArrayBuffer類型,所以需要先轉成視圖才能讀取裡面的資料 var result = new DataView(rResult.target.result); // 把檔案每個位元組推入視圖 for (var i = 0; i < rResult.target.result.byteLength ; i++) { dataview.setUint8(i + arr.length, result.getUint8(i)); } // 調用上傳方法 SendFileToServer(filename, buffer); }; // 讀取檔案,該方法會觸發load事件,並將產生的ArrayBuffer賦予reader.result。 reader.readAsArrayBuffer(file); }; }});
伺服器端代碼如下:
[ServiceContract]public class PictureService{ [OperationContract] [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)] public bool SendPicture(Stream imageContext) { // 讀取位元據 byte[] m_Bytes = ReadToEnd(imageContext); // 擷取第二段的長度 int len = (int)m_Bytes[0]; // 從位元據中複製出第二段資料 byte[] data = new byte[len]; Array.Copy(m_Bytes, 1, data, 0, len); // 將複製出的資料轉換成字串,然後通過jsonConvert還原序列化為ImgInfo對象 string Jsonstr = System.Text.Encoding.Default.GetString(data); ImgInfo imgInfo = JsonConvert.DeserializeObject(Jsonstr); // 讀取圖片檔案資料 byte[] Imagedata = new byte[m_Bytes.Length - 1 - len]; Array.Copy(m_Bytes, 1 + len, Imagedata, 0, m_Bytes.Length - 1 - len); // 判斷儲存目錄是否存在,若不存在則建立 string filePath = @"D:\Image\"; if (!System.IO.Directory.Exists(filePath)) { System.IO.Directory.CreateDirectory(filePath); } // 組建檔案名稱 string imageName = DateTime.Now.ToString("yyyyMMDDhhmmss.") + imgInfo.FileExtName; string imageFullPath = filePath + imageName; // 若檔案已存在,則放棄 if (!File.Exists(imageFullPath)) { try { // 將擷取的位元據寫入檔案 System.IO.File.WriteAllBytes(imageFullPath, Imagedata); imageContext.Close(); return true; } catch { return false; } } else { return false; } } public byte[] ReadToEnd(System.IO.Stream stream) { long originalPosition = 0; if (stream.CanSeek) { originalPosition = stream.Position; stream.Position = 0; } try { byte[] readBuffer = new byte[4096]; int totalBytesRead = 0; int bytesRead; while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0) { totalBytesRead += bytesRead; if (totalBytesRead == readBuffer.Length) { int nextByte = stream.ReadByte(); if (nextByte != -1) { byte[] temp = new byte[readBuffer.Length * 2]; Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length); Buffer.SetByte(temp, totalBytesRead, (byte)nextByte); readBuffer = temp; totalBytesRead++; } } } byte[] buffer = readBuffer; if (readBuffer.Length != totalBytesRead) { buffer = new byte[totalBytesRead]; Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead); } return buffer; } finally { if (stream.CanSeek) { stream.Position = originalPosition; } } } public class ImgInfo { /// /// 檔案類型:身份證、營業執照、上崗證、其它認證 /// public int ImageType { get; set; } /// /// 副檔名 /// public string FileExtName { get; set; } /// /// 會話Id /// public string SessionId { get; set; } }}