我正在上傳圖像到我的服務器上傳圖片時,我試圖向用戶顯示上傳的進度條。但是在NSURLConnection委託方法connection: didSendBodyData: totalBytesWritten: totalBytesExpectedToWrite:
中,我收到了令人困惑的數字。可以說我的數據是X字節長。起初,我得到totalBytesExpectedToWrite爲X,但是在totalBytesWritten達到totalBytesExpectedToWrite後,我的連接仍然繼續,上傳和totalBytesExpectedToWrite移至2X。它總是2X,我不知道爲什麼。連接是相同的(由id),我只調用一次。NSURLConnection發送數據兩次
這裏是我的圖片上傳代碼:
- (void)uploadImage:(UIImage *)image
{
// random boundary string
NSString *boundary = @"----8745633765875256----";
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSMutableData *requestData = [[NSMutableData alloc] init];
// append boundary and separate it with new line
[requestData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting up header files, appending image and separating body with boundary
[requestData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"ad_image\"; filename=\"%@\"\r\n", @"tmp.jpg"] dataUsingEncoding:NSUTF8StringEncoding]];
[requestData appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[requestData appendData:imageData];
[requestData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// initializing request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@&user_id=%@&api_key=%@", kUrlImageTempAdd, userID, apiKey]]];
[request setHTTPMethod:@"POST"];
// setting up content-type "form" to multipart/form-data for image upload
[request addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:requestData];
//setting up content length
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-
// connection init and start
NSURLConnection *connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:true] autorelease];
}
,這裏是我的委託方法:
- (void)connection:(NSURLConnection *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
NSLog(@"connection %@ bytes sent %d/%d (%f%%)", connection, totalBytesWritten, totalBytesExpectedToWrite, ((float)totalBytesWritten/(float)totalBytesExpectedToWrite) * 100.0f);
}
任何建議,爲什麼會這樣?我失去了我的心在這裏:)
發佈日誌還... –