我正在将图像上传到我的服务器,当我上传图像时,我试图向用户显示上传的进度条。但是在 NSURLConnection 委托方法中connection:
didSendBodyData: totalBytesWritten: totalBytesExpectedToWrite:
,我得到了令人困惑的数字。假设我的数据是 X 字节长。起初我得到totalBytesExpectedToWrite 为X,但在totalBytesWritten 达到totalBytesExpectedToWrite 之后,我的连接仍然在进行上传,并且totalBytesExpectedToWrite 转移到2X。它总是正好是 2X,我不知道为什么。连接是相同的(按 id),我只调用它一次。
这是我上传图片的代码:
- (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);
}
有什么建议为什么会发生这种情况?我在这里失去理智:)