Upload Using AFNetworking

牧云@^-^@ 提交于 2019-12-12 18:05:46

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/13656868/upload-using-afnetworking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!