Post not yet marked as solved
Post marked as unsolved with 2 replies, 4,932 views
I've looked into a good number of articles on how to do a multipart/form-data POST on iOS, but none really explain what to do if there were normal parameters as well as the file upload.I have used the multipart/form-data POST on iOS & I had written the following code and it is uploading data but not image data - (void)postWithImage:(NSDictionary *)dictionary{ NSString *urlString = [NSString stringWithFormat:@"YourHostString"]; NSURL *url = [NSURL URLWithString:urlString]; NSString *boundary = @"----1010101010"; // define content type and add Body Boundry NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; NSMutableData *body = [NSMutableData data]; [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; NSEnumerator *enumerator = [dictionary keyEnumerator]; NSString *key; NSString *value; NSString *content_disposition; while ((key = (NSString *)[enumerator nextObject])) { if ([key isEqualToString:@"file"]) { value = (NSString *)[dictionary objectForKey:key]; NSData *postData = UIImageJPEGRepresentation([UIImage imageNamed:value], 1.0); [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\";\r\nfilename=\"screen.png\"\r\n\r\n",value] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:postData]; } else { value = (NSString *)[dictionary objectForKey:key]; content_disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key]; [body appendData:[content_disposition dataUsingEncoding:NSUTF8StringEncoding]]; NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:value options:NSJSONWritingPrettyPrinted error:&error]; [body appendData:jsonData]; //[body appendData:[value dataUsingEncoding:NSUTF8StringEncoding]]; } [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; } //Close the request body with Boundry [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; [request addValue:[NSString stringWithFormat:@"%d", body.length] forHTTPHeaderField: @"Content-Length"]; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; NSLog(@"%@", returnString);}Can anyone please help me to get why image data is not uploading