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];

我正在尝试使用 AFNetworking 从 iphone 上传图像,但这不起作用。formdata appenddata 命令之前的 NSLog 被注销。但之后的那个似乎没有。我还检查了 NSdata 是否为零,但事实并非如此。并且 obv 请求没有被发送。请任何人都可以帮助我。

4

1 回答 1

3

假设您必须上传图像,为什么要NSDictionary使用data? 没必要,你只需要使用datainside multipartFormRequestWithMethod

尝试以下

// 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.

于 2012-12-04T08:05:59.250 回答