OGeek|极客世界-中国程序员成长平台

标题: ios - 上传图片到 Cloudinary IOS [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:41
标题: ios - 上传图片到 Cloudinary IOS

我无法通过 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 = @"OST";
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"参数中时,一切正常。



Best Answer-推荐答案


我对 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 = @"OST";

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






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4