Send Image as a binary file to the server

2020-04-24 11:07发布

问题:

The below is the attribute where I send my image to the server to get the information about the image.

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

To upload the image am using the code below :

    NSData *imageData = UIImageJPEGRepresentation(image, 0.1);

But the parameter is asking me to provide the url.Is there any way that as soon as I snap a photo and upload it to server and get that url and append that in the parameter or any alternative to be found.And am using Unirest http library to send the request.

回答1:

In order to transmit an image captured with the camera to CamFind API using Unirest, you need to same the image first.

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