我无法通过HTTPS POST请求将图像上传到Cloudinary托管,我想使用简单的API方法而不是SDK。我在将图像格式化为字节数组缓冲区中或作为Base64编码时遇到问题。

这是我的代码:

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'参数中时,一切正常。

最佳答案

我没有Cloudinary 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];

关于ios - 将图像上传到Cloudinary IOS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41812907/

10-10 20:47