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];
I am Trying to upload the image from the iphone using AFNetworking, but this is not working. The NSLog just before formdata appenddata command is logged out. But the one after that doesnt seem to. I have also checked if NSdata is nil and thats also not the case. And obv the request is not being sent. Please can anyone help me.
Assuming that you have to upload an image, why are you creating an NSDictionary
with the data
? It is not necessary, you just need to use data
inside multipartFormRequestWithMethod
.
Try the following
// 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];
You should also double check if your server side expects some parameters, because you are setting the NSMutableURLRequest
parameters' field to nil
.