2017-01-23 5 views
2

이미지를 CloudSight 호스팅에 HTTPS POST 요청을 통해 업로드 할 수 없습니다. SDK 대신 간단한 API 메소드를 사용하고 싶습니다. 바이트 배열 버퍼 나 Base64로 이미지를 포맷하는 데 문제가 있습니다.이미지를 Cloudday에 업로드 IOS

UIImage *image = [UIImage imageNamed:@"image.png"]; 
NSData *imageData = UIImagePNGRepresentation(image); 
NSString *strImageData = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; 

NSURL *url = [NSURL URLWithString:@"https://api.cloudinary.com/v1_1/MYSECTER/image/upload"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
request.HTTPMethod = @"POST"; 
NSString *strRequest = [NSString stringWithFormat:@"file=%@&upload_preset=MYSECTER", strImageData]; 
request.HTTPBody = [strRequest dataUsingEncoding:NSUTF8StringEncoding]; 

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { 

    NSDictionary *recievedData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error]; 

    NSLog(@"RECEIVED: %@", recievedData); 

}] resume]; 

불행히도받는 서버에서 대답은 다음과 같습니다 : "지원되지 않는 소스 URL ..."

정말 다른 방법이 많이 시도하지만, 내가 할 수있는 '여기

내 코드입니다 그것을 작동시키지 마십시오.

업데이트 : URL 링크를 'file'매개 변수에 입력하면 정상적으로 작동합니다.

답변

0

나는 해결책을 찾아, 그것은 아주 좋은 작품 : 여기에 설명 된대로

// image for sending 
UIImage *image = [UIImage imageNamed:@"image.png"]; 

// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept. 
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init]; 
[_params setObject:@"SECKET_PRESET" forKey:@"upload_preset"]; 

// the boundary string : a random string, that will not repeat in post data, to separate post data fields. 
NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy"; 

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ 
NSString* FileParamConstant = @"file"; 

// the server url to which the image (or the media) is uploaded. Use your server url here 
NSURL* requestURL = [NSURL URLWithString:@"https://api.cloudinary.com/v1_1/SECKET_KEY/image/upload"]; 

// create request 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; 
[request setHTTPShouldHandleCookies:NO]; 
[request setTimeoutInterval:30]; 
[request setHTTPMethod:@"POST"]; 

// set Content-Type in HTTP header 
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant]; 
[request setValue:contentType forHTTPHeaderField: @"Content-Type"]; 

// post body 
NSMutableData *body = [NSMutableData data]; 

// add params (all params are strings) 
for (NSString *param in _params) { 
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]]; 
} 

// add image data 
NSData *imageData = UIImagePNGRepresentation(image); 
if (imageData) { 
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:imageData]; 
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
} 

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 

// setting the body of the post to the reqeust 
[request setHTTPBody:body]; 

// set the content-length 
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

// set URL 
[request setURL:requestURL]; 

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { 

    NSDictionary *recievedData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error]; 

    NSLog(@"RECEIVED: %@", recievedData); 

}] resume]; 
0

Cloudine API에 대한 경험이 없지만 도움이 되었기를 바랍니다. 나는 'Uploading with a direct call to the API'에 대한 문서를 보았습니다.

필자는 '파일'과 'upload_preset'을 POST 매개 변수 (본문의 데이터로 연결되지 않음)로 제공해야한다고 생각합니다.

UIImage *image = [UIImage imageNamed:@"image.png"]; 
NSData *imageData = UIImagePNGRepresentation(image); 
NSString *strImageData = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; 

NSURL *url = [NSURL URLWithString:@"https://api.cloudinary.com/v1_1/MYSECTER/image/upload"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
request.HTTPMethod = @"POST"; 

// Replace this: 

//NSString *strRequest = [NSString stringWithFormat:@"file=%@&upload_preset=MYSECTER", strImageData]; 
//request.HTTPBody = [strRequest dataUsingEncoding:NSUTF8StringEncoding]; 

// With this: 

NSString *imageDataStr = [[NSString alloc] initWithData:imageData encoding:NSUTF8StringEncoding]; 
[request setValue:imageDataStr forHTTPHeaderField:@"file"]; 
[request setValue:@"MYSECTER" forHTTPHeaderField:@"upload_preset"]; 


[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { 

    NSDictionary *recievedData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error]; 

    NSLog(@"RECEIVED: %@", recievedData); 

}] resume]; 
+0

안녕, 시간 내 주셔서 감사합니다,하지만 작동하지 않습니다. "필요한 매개 변수가 없습니다 - 파일";라는 오류 메시지가 나타납니다. –

0

당신은 업로드 이미지 작업을 수행하기 위해 Cloudinary의 SDK를 사용할 수 있습니다 다음 http://cloudinary.com/blog/direct_upload_made_easy_from_browser_or_mobile_app_to_the_cloud

코드 샘플은 iOS 용 Objective-C에서 직접 서명되지 않은 업로드 API 호출을 보여줍니다. ...

CLCloudinary *cloudinary = [[CLCloudinary alloc] init]; 
[cloudinary.config setValue:@"demo" forKey:@"cloud_name"]; 

NSString *imageFilePath = [[NSBundle mainBundle] pathForResource:@"logo" 
ofType:@"png"]; 

CLUploader* uploader = [[CLUploader alloc] init:cloudinary delegate:self]; 
[uploader unsignedUpload:imageFilePath uploadPreset:@"zcudy0uz" options:@{}]; 

다음 코드 샘플은 user_sample_image_1002의 사용자 지정 공용 ID 지정, 나중에 업로드 된 이미지 액세스 및 이미지 관리를 단순화하기위한 태그 지정 등보다 고급 예제를 보여줍니다. 또한 실시간 이미지 조작을 수행하는 동적 URL을 작성하는 예를 보여줍니다. 애플리케이션에 포함하기 위해 업로드 된 이미지의 150x100 얼굴 탐지 기반 축소판을 생성합니다.

NSData *imageData = [NSData dataWithContentsOfFile:imageFilePath]; 

[uploader unsignedUpload:imageData uploadPreset:@"zcudy0uz" options: 
[NSDictionary dictionaryWithObjectsAndKeys:@"user_sample_image_1002", 
@"public_id", @"tags", @"ios_upload", nil] withCompletion:^(NSDictionary 
*successResult, NSString *errorResult, NSInteger code, id context) { 

    if (successResult) { 

     NSString* publicId = [successResult valueForKey:@"public_id"]; 
     NSLog(@"Upload success. Public ID=%@, Full result=%@", publicId, 
     successResult); 
     CLTransformation *transformation = [CLTransformation transformation]; 
     [transformation setWidthWithInt: 150]; 
     [transformation setHeightWithInt: 100]; 
     [transformation setCrop: @"fill"]; 
     [transformation setGravity:@"face"]; 

     NSLog(@"Result: %@", [cloudinary url:publicId 
     options:@{@"transformation": 
     transformation, @"format": @"jpg"}]);     

    } else { 

     NSLog(@"Upload error: %@, %d", errorResult, code);    

     } 

} andProgress:^(NSInteger bytesWritten, NSInteger totalBytesWritten, 
    NSInteger totalBytesExpectedToWrite, id context) { 
    NSLog(@"Upload progress: %d/%d (+%d)", totalBytesWritten, 
    totalBytesExpectedToWrite, bytesWritten); 
}];