gpt4 book ai didi

ios - 上传图片到Cloudinary IOS

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:54:09 25 4
gpt4 key购买 nike

我无法通过 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com