我无法通过 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”上的文档'.
我认为您需要提供"file"和“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/