title: iOS - Uploading image by HTTP POST
body: <p><strong>GOAL</strong>: I would like to upload an image (<em>UIImage</em>) to server by HTTP POST method.</p>
  
  <p><strong>PROBLEM</strong>: I get a response "<strong>You did not select a file to upload.</strong>" (status = 200)</p>
  
  <p><strong>HINT</strong>: Here is a java code from Android application that works:</p>
  
  <pre><code>public static String sendImage(String url, String username, String password, String filePath) {
      try {
          File file = new File(filePath);
          int fileSize = (int) (file.length() / 1024);
          if (fileSize &lt; 2048 &amp;&amp; fileSize &gt; 0) {
              HttpClient httpClient = new DefaultHttpClient();
              AuthScope authScope = new AuthScope(HOST, 80);
              UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
              ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, usernamePasswordCredentials);
              BasicHttpContext localHttpContext = new BasicHttpContext();
              BasicScheme basicScheme = new BasicScheme();
              localHttpContext.setAttribute("preemptive-auth", basicScheme);
  
              HttpHost targetHttpHost = new HttpHost(HOST, 80, "http");
              HttpPost httpPost = new HttpPost(url);
              httpPost.setHeader("enctype", "multipart/form-data");
  
              MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
              multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
              multipartEntity.addPart("userfile", new FileBody(file));
              httpPost.setEntity(multipartEntity.build());
  
              HttpResponse httpResponse = httpClient.execute(targetHttpHost, httpPost, localHttpContext);
  
              int statusCode = httpResponse.getStatusLine().getStatusCode();
              String reason = httpResponse.getStatusLine().getReasonPhrase();
  
              Log.d(TAG, "Status code: " + statusCode + " " + reason + "\n" + EntityUtils.toString(httpResponse.getEntity()));
              return "Status code: " + statusCode + " " + reason;
          } else {
              return "Please select image smaller than 200 kB";
          }
      } catch (Exception e) {
          Log.e(TAG, "Exception: " + e.toString());
      }
      return null;
  }
  </code></pre>
  
  <p><strong>MY CODE</strong>:</p>
  
  <pre><code>+ (void)uploadPhotoToUserWithID:(int)userID photo:(UIImage *)photo
  {
      // Convert UIImage to JPEG
      NSData *imageData = UIImageJPEGRepresentation(photo, 0.5);
  
      // Create request
      NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://XXX:XXX@example.com/upload/id/89"]];
  
      [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
      [request setHTTPShouldHandleCookies:NO];
      [request setTimeoutInterval:30];
      [request setHTTPMethod:@"POST"];
  
      NSString *boundary = @"unique-consistent-string";
  
      // Post body
      NSMutableData *body = [[NSMutableData alloc] init];
  
      // Add image data
      if (imageData)
      {
          [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
          [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@; filename=\"imageName.jpg\"\r\n", @"\"userfile\""] 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", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
  
      // Setting the body of the post to the reqeust
      [request setHTTPBody:body];
  
      // Set Content-Type in HTTP header
      NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
      [request setValue:contentType forHTTPHeaderField: @"enctype"];
      NSString *postLength = [NSString stringWithFormat:@"%d", body.length];
      [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
  
      [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
      {
          if(data.length &gt; 0)
          {
              NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
              NSLog(@"%i", httpResponse.statusCode);
          }
      }];
  }
  </code></pre>