2012-12-01 92 views
2
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1:8000/photo/"]; 
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; 
NSDictionary *headers = [NSDictionary dictionaryWithObject:data forKey:@"attachment"]; 
//NSLog(@"strimng"); 
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"upload/" parameters:nil constructingBodyWithBlock: ^(id<AFMultipartFormData> formData) { 
    NSLog(@"strimng"); 
    [formData appendPartWithFileData:data name:@"attachment" fileName:@"attachment.jpg" mimeType:@"image/jpeg"]; 
    NSLog(@"strimng"); 
}]; 
NSLog(@"strimng"); 
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { 
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite); 
}]; 
[operation start]; 

我想從AF上傳圖像使用AFNetworking,但這是行不通的。 在formdata appenddata命令之前的NSLog被註銷。但之後的那個似乎不是。我也檢查過NSdata是否爲零,那也不是這種情況。並且obv請求沒有被髮送。 請任何人都可以幫助我。上傳使用AFNetworking

回答

3

假設您必須上傳圖片,爲什麼要創建NSDictionarydata?這是沒有必要的,你只需要在multipartFormRequestWithMethod內使用data

請嘗試以下

// Get the image that you want to upload via ImagePicker or a @property 
UIImage *imageIWantToUpload = self.image; 

// Create the NSData object for the upload process 
NSData *dataToUpload = UIImageJPEGRepresentation(imageIWantToUpload, 0.5); 

NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"upload/" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
    [formData appendPartWithFileData:dataToUpload name:@"attachment" fileName:@"attachment.jpg" mimeType:@"image/jpg"]; 
}]; 

// You can add then the progressBlock and the completionBlock 
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
[operation setUploadProgressBlock:progress]; 
[operation setCompletionBlockWithSuccess:success failure:failure]; 

您應該如果您的服務器端預計一些參數,因爲你的NSMutableURLRequest參數字段設置爲nil也仔細檢查。

+0

但是,正如你所看到的,我並沒有在任何地方使用它......這只是嘗試如果這項工作。沒有我的服務器不需要參數。 –

+0

確保你在服務器端期待'''name =「attachment」'''。忘了1h搞清楚:) –