Send image to server on iphone

I want to send / share the image on the server from iphone. Image is ready for publication. I use a way to display most sites using the code below.

NSData *imageData = UIImageJPEGRepresentation(image, 100); NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; NSString *boundary = @"0x0hHai1CanHazB0undar135"; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; [request setValue:contentType forHTTPHeaderField:@"Content-Type"]; NSMutableData *body = [NSMutableData data]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding: NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"imageToAttach\"; filename=\"%@\"\r\n",fileName]dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:imageData]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; NSLog(@"%@",returnString); 

but it gives me some internal server error, and then I indicated that the server is requesting image stream bytes. How can I convert the image to a stream and then send this stream to the server?

+4
source share
5 answers

Giving the same answer 2 Time. How to convert image to binary format in iOS?

You can use the CoreGraphics ' UIImagePNGRepresentation(UIImage *image) method, which returns an NSData and saves it. and if you want to convert it to UIImage , create it using the [UIimage imageWithData:(NSData *data)] method.

 - (void)sendImageToServer { UIImage *yourImage= [UIImage imageNamed:@"image.png"]; NSData *imageData = UIImagePNGRepresentation(yourImage); NSString *postLength = [NSString stringWithFormat:@"%d", [imageData length]]; // Init the URLRequest NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setHTTPMethod:@"POST"]; [request setURL:[NSURL URLWithString:[NSString stringWithString:@"http://yoururl.domain"]]]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody:imageData]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (connection) { // response data of the request } [request release]; } 
+22
source

I used this code in my application and it works great ...

 //create request NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; //Set Params [request setHTTPShouldHandleCookies:NO]; [request setTimeoutInterval:60]; [request setHTTPMethod:@"POST"]; //Create boundary, it can be anything NSString *boundary = @"------VohpleBoundary4QuqLuM1cE5lMwCy"; // set Content-Type in HTTP header NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; // post body NSMutableData *body = [NSMutableData data]; //Populate a dictionary with all the regular values you would like to send. NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init]; [parameters setValue:param1 forKey:@"param1-name"]; [parameters setValue:param2 forKey:@"param2-name"]; [parameters setValue:param3 forKey:@"param3-name"]; // add params (all params are strings) for (NSString *param in parameters) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"%@\r\n", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]]; } NSString *FileParamConstant = @"imageParamName"; NSData *imageData = UIImageJPEGRepresentation(imageObject, 1); //Assuming data is not nil we add this to the multipart form if (imageData) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:imageData]; [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; } //Close off the request with the boundary [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; // setting the body of the post to the request [request setHTTPBody:body]; // set URL [request setURL:[NSURL URLWithString:baseUrl]]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; if ([httpResponse statusCode] == 200) { NSLog(@"success"); } }]; 
+6
source

I used this code

 // create request NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; [request setHTTPShouldHandleCookies:NO]; [request setTimeoutInterval:30]; [request setHTTPMethod:@"POST"]; //Create boundary, it can be anything NSString *boundary = @"------VohpleBoundary4QuqLuM1cE5lMwCy"; // set Content-Type in HTTP header NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; // post body NSMutableData *body = [NSMutableData data]; // add params (all params are strings) for (NSString *param in _params) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]]; } // add image data NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0); if (imageData) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:imageData]; [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; } [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; // setting the body of the post to the reqeust [request setHTTPBody:body]; // set the content-length NSString *postLength = [NSString stringWithFormat:@"%d", [body length]]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; // set URL [request setURL:requestURL]; 

It works like a charm.

+2
source

Can you see the following code, I hope you find it useful.

Here is the iOS code

 -(void)createConnectionRequestToURL:(NSString *)urlStr withImage:(UIImage*)image withImageName:(NSString*)imageName { NSData *imageData = UIImageJPEGRepresentation(image, 90); NSString *urlString = urlStr; // setting up the request object now NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSString *boundary = [[NSString alloc]init]; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; NSMutableData *body = [NSMutableData data]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\"rn" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Type: application/%@.jpg\r\n\r\n",imageName] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:imageData]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; //Using Synchronous Request. You can also use asynchronous connection and get update in delegates NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; NSLog(@"--------%@",returnString); } 

Find server-side (PHP) encoding for the image. Download with a random name. he will also give a link to the image as an answer.

 //Create a folder named images in your server where you want to upload the image. // And Create a PHP file and use below code . <?php $uploaddir = 'images/'; $ran = rand () ; $file = basename($_FILES['userfile']['name']); $uploadfile = $uploaddir .$ran.$file; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { echo "www.host.com/.../images/{$uploadfile}"; } ?> 

(OR)

 <?php $request_body = @file_get_contents('php://input'); foreach (getallheaders() as $name => $value) { if ($FileName=="FileName") { $header=$value; break; } } $uploadedDir = "directory/"; @mkdir($uploadedDir); file_put_contents($uploadedDir."/".$FileName.".txt", $request_body.PHP_EOL, FILE_APPEND); header('X-PHP-Response-Code: 202', true, 202); 

? >

+1
source

I used this code and it works great.

If you want more accuracy and speed, you can compress the image and then download, but compression is an optional part.

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; [request setHTTPShouldHandleCookies:NO]; [request setTimeoutInterval:30]; [request setHTTPMethod:@"POST"]; // RP: Empaquetando datos NSMutableDictionary* _params = [[NSMutableDictionary alloc] init]; [_params setObject:[NSString stringWithFormat:@"%@",loginoneid] forKey:@"user_id"]; [_params setObject:[NSString stringWithFormat:@"%@",_strpostid] forKey:@"post_id"]; // the boundary string : a random string, that will not repeat in post data, to separate post data fields. NSString *BoundaryConstant = @"V2ymHFg03ehbqgZCaKO6jy"; // string constant for the post parameter 'file' NSString *FileParamConstant = @"files[]"; //RP: Configurando la direcciรณn NSURL *requestURL = [[NSURL alloc] initWithString:@"http://www.hugosys.in/www.nett-torg.no/api/rpcs/uploadfiles/"]; // set Content-Type in HTTP header NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant]; [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; // post body NSMutableData *body = [NSMutableData data]; // add params (all params are strings) for (NSString *param in _params) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]]; } if (imageData) { printf("appending image data\n"); [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\'%@\'; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:imageData]; [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; } [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; // setting the body of the post to the reqeust [request setHTTPBody:body]; // set the content-length // set the content-length NSString *postLength = [NSString stringWithFormat:@"%d", [body length]]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; // set URL [request setURL:requestURL]; NSURLResponse *response = nil; NSError *err = nil; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; dispatch_async(dispatch_get_main_queue(), ^{ NSString *str = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding]; 
0
source

Source: https://habr.com/ru/post/1479685/


All Articles