9039

Sending NSData and NSString in the same POST

Question:

I am trying to follow this <a href="https://stackoverflow.com/questions/4300935/insert-imagedata-into-mysql-database-from-xcode-using-php-json" rel="nofollow">Insert imagedata into MySQL database from XCode using PHP & JSON</a> answer to send a photo from my app to a MySQL database but I am confused as to how to add an NSString ID to reference to the POST body.

We have the following to create the body which gets the image data:

NSMutableData *body = [NSMutableData data]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"imagename.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:imageData]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; // setting the body of the post to the reqeust [request setHTTPBody:body];

How might I send additional information such as a text ID within the same post?

Answer1:

Here is the whole code to post data along with Imagedata and string.

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; [request setHTTPMethod:@"POST"]; NSString *boundary = @"---------------------------14737809831466499882746641449"; 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:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"imagename.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:imageData]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; [dict setObject:@"<YOUR TEXT>" forKey:@"<KEY>"]; [body appendData:[self createFormData:dict withBoundary:boundary]]; [request setHTTPBody:body]; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; NSLog(@"%@", returnString); - (NSData*)createFormData:(NSDictionary*)myDictionary withBoundary:(NSString*)myBounds { NSMutableData *myReturn = [[NSMutableData alloc] init]; NSArray *formKeys = [myDictionary allKeys]; for (int i = 0; i < [formKeys count]; i++) { [myReturn appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",myBounds] dataUsingEncoding:NSASCIIStringEncoding]]; [myReturn appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n%@",[formKeys objectAtIndex:i],[myDictionary valueForKey:[formKeys objectAtIndex:i]]] dataUsingEncoding:NSASCIIStringEncoding]]; } return myReturn; }

Answer2:

I think what you are looking for is setValue:forHTTPHeaderField:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com"]]; request.HTTPMethod = @"POST"; request.HTTPBody = body; [request setValue:@"someValue" forHTTPHeaderField:@"someField"];

Recommend

  • Indexing documents using Solr results in Expected mime type application/octet-stream but got text/ht
  • NSString to NSData Failing in Encoding
  • Missing Content-Length header when using Nginx + Gzip + Unicorn
  • Swift parse html table
  • Youtube v3 api 401 Unauthorized
  • How to send a file AND other POST data with Synapse
  • UIWebview manipulating SVG 'on the fly'
  • getting base64 content string of an image from a mimepart in Java
  • Change UISearchBar background image in iOS11
  • Refresh tableview after delete a tableview cell and refresh view controller
  • Html string convert into attributed string with \\U00002028\\n ios
  • CSS background-image won't show with short URL
  • Adding padding and border to an UIImageView
  • Prevent redirect response with Alamofire in Swift
  • Deleting in NSDocumentDirectory
  • How create UIImage from bytes?
  • Loading huge Text file in UITextview crashes
  • Error Domain=NSCocoaErrorDomain Code=3840 “Invalid value around character 0.” UserInfo={NSDebugDescr
  • Determine if UTF-8 encoded NSData contains a null-terminated string
  • PHP file_exists() anomaly
  • MVVM: Image Bind Source from FileOpenPicker
  • Unzip archive in .Net CORE 1.0
  • Streaming screenshots over WebRTC as a video stream from iOS
  • Connect .sks to skscene.h
  • Play WS (2.2.1): post/put large request
  • Bad request using file_get_contents for PUT request in PHP
  • Syntax for setting draggablecursor property in google maps api
  • C# - Serializing and deserializing static member
  • DotNetZip - Calculate final zip size before calling Save(stream)
  • Resize panoramic image to fixed size
  • Sending data from AppleScript to FileMaker records
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • How to include full .NET prerequisite for Wix Burn installer
  • Load html files in TinyMce
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • Free memory of cv::Mat loaded using FileStorage API
  • How do I configure my settings file to work with unit tests?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Is it possible to post an object from jquery to bottle.py?
  • Binding checkboxes to object values in AngularJs