ios - 将图像作为二进制文件发送到服务器

标签 ios objective-c

下面是我将图像发送到服务器以获取有关图像的信息的属性。

    NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"en_US", @"image_request[locale]", @"en", @"image_request[language]",[NSURL URLWithString:@"<file url>"], @"image_request[image]", nil];

使用下面的代码上传图片:

    NSData *imageData = UIImageJPEGRepresentation(image, 0.1);

但是参数要求我提供 url。有什么方法可以让我在拍摄照片并将其上传到服务器并获取该 url 并将其附加到参数或任何可找到的替代方案中。我使用 Unirest http 库发送请求。

最佳答案

为了使用 Unirest 将用相机拍摄的图像传输到 CamFind API,您需要先复制图像。

// Get the path to the Documents folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = [paths objectAtIndex:0];

// Get the path to an file named "tmp_image.jpg" in the Documents folder
NSString *imagePath = [documentDirectoryPath stringByAppendingPathComponent:@"tmp_image.jpg"];
NSURL *imageURL = [NSURL fileURLWithPath:imagePath];

// Write the image to an file called "tmp_image.jpg" in the Documents folder
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
[imageData writeToURL:imageURL atomically:YES];

// Now construct the parameters that will be passed to Unirest
NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"en_US", @"image_request[locale]", @"en", @"image_request[language]", imageURL, @"image_request[image]", nil];

// And the headers
NSDictionary* headers = [NSDictionary dictionaryWithObjectsAndKeys:@"<mashape-key>", @"X-Mashape-Authorization", nil];

// Call the API using Unirest
HttpJsonResponse* response = [[Unirest post:^(BodyRequest* request) {
    [request setUrl:@"https://camfind.p.mashape.com/image_requests"];
    [request setHeaders:headers];
    [request setParameters:parameters];
}] asJson];

关于ios - 将图像作为二进制文件发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19380980/

相关文章:

ios - 使用 AutoLayout 在 UIScrollView 中居中固定 UIView

ios - 如何在 iOS 项目之间共享实用程序类?

ios - 下载完成时通过 NSURLSession/NSURLSessionDownloadTask 发送本地通知

iphone - 如何在 Iphone 中使用 Google Maps API?

iphone - 添加 View 时崩溃 (SIGABRT)。 ( WebView )

ios - 在 xib 中设置用于单击和双击的 UIGestureRecognizers

ios - 如何让 NSTimer 在满足条件后停止重复

ios - 无法从 iOS 应用程序访问 Firebase 存储默认存储桶

ios - AVAssetWriter:指定关键帧

ios - 如何使 UILabel 的一部分在视觉上成为 block 引用?