要讓 iOS 把圖片傳到 WCF 服務端,網路上找得到大量 WCF 收檔案的範例,也找得到大量 iOS 送圖片的範例,但兩者「接起來」的完整說明卻很少。本文記錄一次實作過程與踩到的坑。
直覺的做法是 Base64 編碼後上傳,實作簡單。但筆者想要的是「網路串流」——如此一來,未來 iOS 要送任何檔案,伺服器端都不必再改。想法簡單,過程卻相當曲折。
使用 AFNetworking,關鍵只有一行:
NSString *filename = @"test.jpg";
AFHTTPRequestOperationManager *AFManager =
[[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@FileTranUrl]];
AFHTTPRequestOperation *operation =
[AFManager POST:path parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formdata) {
[formdata appendPartWithFileData:imagedata name:name fileName:filename mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) { success(operation, responseObject); }
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) { failure(operation, error); }
}];
其中 imagedata 是 UIImage 轉出的 NSData。
那麼 AFMultipartFormData 究竟做了什麼?看它的原始碼:
- (void)appendPartWithFileData:(NSData *)data name:(NSString *)name
fileName:(NSString *)fileName mimeType:(NSString *)mimeType {
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName]
forKey:@"Content-Disposition"];
[mutableHeaders setValue:mimeType forKey:@"Content-Type"];
[self appendPartWithHeaders:mutableHeaders body:data];
}
- (void)appendPartWithHeaders:(NSDictionary *)headers body:(NSData *)body {
AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
bodyPart.stringEncoding = self.stringEncoding;
bodyPart.headers = headers;
bodyPart.boundary = self.boundary;
bodyPart.bodyContentLength = [body length];
bodyPart.body = body;
[self.bodyStream appendHTTPBodyPart:bodyPart];
}
看到 appendHTTPBodyPart: 這一步就明白了:所有資料最終都被放進網路串流,而且帶著 boundary、Content-Disposition、Content-Type 這些標頭。之所以要追這段原始碼,是因為 WCF 需要「契約(Contract)」定義,我們必須知道對方送來的到底是什麼格式。
由此可推得契約簽名:
void Upload(Stream requestStream)
接著調整 web.config,把傳輸模式改為串流並放寬大小限制:
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="WebConfiguration" maxBufferSize="65536"
maxReceivedMessageSize="2000000000" transferMode="Streamed" />
</webHttpBinding>
</bindings>
<services>
<service name="WcfServiceForIOS.ServiceForIOSFile" behaviorConfiguration="ServiceBehavior">
<endpoint address="" binding="webHttpBinding" behaviorConfiguration="web"
bindingConfiguration="WebConfiguration"
contract="WcfServiceForIOS.IServiceForIOSFile" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web"><webHttp /></behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
契約實作主體就是把輸入串流逐塊寫入檔案:
using (targetStream = new FileStream(filePathAndName, FileMode.Create, FileAccess.Write, FileShare.None))
{
const int bufferLen = 4096;
Byte[] buffer = new Byte[bufferLen];
int count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
targetStream.Write(buffer, 0, count);
filesize += count;
}
targetStream.Close();
sourceStream.Close();
}
上傳成功、檔案也確實出現在資料夾裡,但點開卻提示「圖片已損壞」。用 Notepad++ 打開這個檔案,內容長這樣:
--Boundary+4AA85CFEE4A1D140 Content-Disposition: form-data; name="file"; filename="test.jpg" Content-Type: image/jpeg (亂碼,就是圖片的二進位資料) --Boundary+4AA85CFEE4A1D140--
是不是覺得很眼熟?這正好印證了前面的分析:傳過來的串流裡「同時包含」了表單標頭與圖片本體,必須拆開處理。
做法與 Web 端處理 form-data 相同:先轉成字串取出各項屬性,再用正則表達式抓出 Content-Type 與 filename,最後依 boundary 切出真正的檔案內容。
private void Parse(Stream stream, Encoding encoding)
{
this.Success = false;
byte[] data = ToByteArray(stream);
requestData = data;
string content = encoding.GetString(data);
int delimiterEndIndex = content.IndexOf("\r\n");
if (delimiterEndIndex > -1)
{
string delimiter = content.Substring(0, delimiterEndIndex);
Regex re = new Regex(@"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
Match contentTypeMatch = re.Match(content);
re = new Regex(@"(?<=filename\=\"")(.*?)(?=\"")");
Match filenameMatch = re.Match(content);
if (contentTypeMatch.Success && filenameMatch.Success)
{
this.ContentType = contentTypeMatch.Value.Trim();
this.Filename = filenameMatch.Value.Trim();
int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
int endIndex = IndexOf(data, delimiterBytes, startIndex);
int contentLength = endIndex - startIndex;
byte[] fileData = new byte[contentLength];
Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);
this.FileContents = fileData;
this.Success = true;
}
}
}
取出各段之後,就能正常寫入檔案,圖片也打得開了。
整個流程的關鍵在於:iOS 用 AFNetworking 送的是標準 multipart/form-data,WCF 端以 Stream 契約接收後拿到的其實是「完整的 multipart 本文」,而不是純檔案位元組。想通這一點,後續要不要支援多檔、要不要泛化成通用上傳服務,都只是解析層的擴充而已。