2013-10-02 56 views
0

我目前正在爲iOS 7開發,但爲了保持兼容性,我確保在iOS 6中一切正常(當然)。我的多部分/表單數據按預期工作在iOS 7中,但在iOS 6中,我的服務器沒有收到任何文件(連接已建立,只有沒有文件)。有什麼我失蹤?multipart/form-data發佈0個文件

// Request 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setURL:[NSURL URLWithString:urlString]]; 
[request setHTTPMethod:@"POST"]; 
NSString *boundary = @"---------------------------14737809831466499882746641449"; 
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; 
[request addValue:contentType forHTTPHeaderField: @"Content-Type"]; 
NSMutableData *body = [NSMutableData data]; 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadedFile\"; filename=\"%@.jpg\"\r\n", deviceId] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[NSData dataWithData:imageData]]; 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

//workaround added here 

[request setHTTPBody:body]; 

//make request 
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
[conn start]; 

編輯:以下行添加到上面的代碼作爲一種解決方法,但我不認爲這是「正確」的方式來執行此。

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

回答

0

看來我不小心刪除了一行代碼。通過過去的提交看,我發現我的問題。我刪除了Content-Type行。

NSMutableData *body = [NSMutableData data]; 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];// Here was my problem 
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadedFile\"; filename=\"%@.jpg\"\r\n", deviceId] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[NSData dataWithData:imageData]]; 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];