我尝试将图片上传到图片识别API,但我得到的是NSHTTPURLResponse
我得到的。
<NSHTTPURLResponse: 0x12f7ce4e0> { URL: https:/api.vize.ai/v1/classify/ } { status code: 400, headers {
Allow = "POST, OPTIONS";
Connection = "keep-alive";
"Content-Language" = en;
"Content-Length" = 37;
"Content-Type" = "application/json";
Date = "Wed, 21 Feb 2018 12:24:17 GMT";
"Referrer-Policy" = "strict-origin";
Server = "nginx/1.13.7";
"Strict-Transport-Security" = "max-age=31536000; includeSubDomains; preload";
Vary = "Accept, Host, Accept-Language, Cookie";
"X-Frame-Options" = DENY;
"X-UA-Compatible" = "IE=Edge,chrome=1";
"x-content-type-options" = nosniff;
"x-xss-protection" = "1; mode=block";
} }
我使用图像选择器选择图像,然后上传它。这是我的实现。
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
// Dismiss image picker
[picker dismissViewControllerAnimated:YES completion:nil];
// Classify image
UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
// Request authorization
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
switch (status) {
case PHAuthorizationStatusAuthorized:
NSLog(@"PHAuthorizationStatusAuthorized");
break;
case PHAuthorizationStatusDenied:
NSLog(@"PHAuthorizationStatusDenied");
break;
case PHAuthorizationStatusNotDetermined:
NSLog(@"PHAuthorizationStatusNotDetermined");
break;
case PHAuthorizationStatusRestricted:
NSLog(@"PHAuthorizationStatusRestricted");
break;
}
}];
// Get image name
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[refURL] options:nil];
NSString *filename = [[result firstObject] filename];
// Get image file path and append file name onto it
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:filename];
[imageData writeToFile:path atomically:YES];
NSDictionary *headers = @{ @"content-type": @"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
@"Content-Type": @"multipart/form-data",
@"Accept": @"application/json",
@"Authorization": @"Token 60f6be2a21bdf731d86a8817b440a1afba692fed",
@"Cache-Control": @"no-cache",
@"Postman-Token": @"7d262730-0c7d-66dc-bbbb-43f40dbfe8ce" };
NSArray *parameters = @[ @{ @"name": @"task", @"value": @"dc9ef71a-b8a0-4a12-90fd-83d717cf887f" },
@{ @"name": @"image_file", @"fileName": path } ];
NSString *boundary = @"----WebKitFormBoundary7MA4YWxkTrZu0gW";
NSError *error;
NSMutableString *body = [NSMutableString string];
for (NSDictionary *param in parameters) {
[body appendFormat:@"--%@\r\n", boundary];
if (param[@"fileName"]) {
[body appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n", param[@"name"], param[@"fileName"]];
[body appendFormat:@"Content-Type: %@\r\n\r\n", param[@"contentType"]];
[body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:/*NSASCIIStringEncoding*/NSASCIIStringEncoding error:&error]]; // here NSUTF8StringEncoding
if (error) {
NSLog(@"%@", error);
}
} else {
[body appendFormat:@"Content-Disposition:form-data; name=\"%@\"\r\n\r\n", param[@"name"]];
[body appendFormat:@"%@", param[@"value"]];
}
}
[body appendFormat:@"\r\n--%@--\r\n", boundary];
NSData *postData = [body dataUsingEncoding:/*NSASCIIStringEncoding*/NSASCIIStringEncoding]; // here NSUTF8StringEncoding
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.vize.ai/v1/classify/"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"%@", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"%@", httpResponse);
}
}];
[dataTask resume];
}
我的问题是什么?
答案 0 :(得分:0)
使用afnetworking进行此操作。 这是工作代码:
-(void)uploadImagetoServer
{
if(self.titleTextField.text.length>0)
{
self.descrptionTxtview.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds));
// NSString *firstName=[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"username"]];
//NSString *lastName=[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"lastname"]];
NSString *fullname=[NSString stringWithFormat:@"%@ %@",[[NSUserDefaults standardUserDefaults] valueForKey:@"firstname"],[[NSUserDefaults standardUserDefaults] valueForKey:@"lastname"]];
NSString * type ;
NSString * userId = [NSString stringWithFormat: @"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"userid"]];
// lastName= [NSString stringWithFormat: @"%@ %@", firstName, lastName];
userInfoDict=[[NSMutableDictionary alloc] init];
[userInfoDict setValue:userId forKey:@"user_id"];
[userInfoDict setValue:fullname forKey:@"username"];
[userInfoDict setValue:@"29" forKey:@"catid"];
[userInfoDict setValue:[NSString stringWithFormat: @"%@", self.titleTextField.text] forKey:@"title"];
[_request setTimeoutInterval:1000];
NSLog(@"Parameters :%@",userInfoDict);
NSString * baseUrl = @"https://justgolive.net/api/Home/videoUpload/";
_request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@",baseUrl] parameters:userInfoDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
NSLog(@"\n\n requrst time out is%f\n\n", [_request timeoutInterval]);
NSData* data = UIImagePNGRepresentation(_imagedRecived);
[formData appendPartWithFileData:data name:@"video" fileName:@"myImage.png" mimeType:@"image/png"];
NSLog(@"\n image upload %@\n\n",_videoUrl);
} error:nil];
// [self.view addSubview:_playerProgress];
// [_playerProgress setHidden:NO];
self.descrptionTxtview.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds));
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
_uploadTask = [manager
uploadTaskWithStreamedRequest:_request
progress:^(NSProgress * _Nonnull uploadProgress)
{
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
// [_btn_sendbutton setHidden:YES];
//Update the progress view
// [_playerProgress setProgress:uploadProgress.fractionCompleted];
// [self.view addSubview:_largestProgressView];
// [_largestProgressView setProgress:uploadProgress.fractionCompleted animated:YES];
NSLog(@"\n uploading image vlaues %f\n",uploadProgress.fractionCompleted);
// for uploading video in background
[self.uploProgressView setHidden:NO];
[self.uploProgressView setProgress:uploadProgress.fractionCompleted animated:YES];
if (uploadProgress.completedUnitCount == 1) {
// [self.navigationController popToRootViewControllerAnimated:YES];
}
manager.attemptsToRecreateUploadTasksForBackgroundSessions=YES;
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
self.descrptionTxtview.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds));
// [_playerProgress setHidden:YES];
} else
{
NSLog(@"%@ ", response);
manager.attemptsToRecreateUploadTasksForBackgroundSessions=NO;
[_playerProgress setHidden:YES];
NSLog(@"\n\n REsponse Form Server %@\n\n",responseObject);
NSArray * ressp = responseObject;
NSError *error;
[[NSFileManager defaultManager] removeItemAtURL:_videoUrl error:&error];
if ([[ressp valueForKey:@"message"] isEqualToString:@"Successfull"]) {
[self.navigationController popToRootViewControllerAnimated:YES];
}
[model setUpLogin:YES];
//
}
}
];
[_uploadTask resume];
[self hideStuffOndoneUploading];
}
else
[self alertControllerMethod:@"Please add story description and try again" forTitle:@"Warning" withTag:nil];
}