0

After some tinkering with a code found in this URL:

How to send post data and image file to server Xcode

I managed to run it without anymore crashes but this time, i get a bad request error that says i have invalid JSON.How do i fix this? Btw,self.choseImage.image is the image i want to upload.

  NSData *imageData = UIImageJPEGRepresentation(self.chosenImage.image,1);

    if (imageData != nil)

    {
        NSString * filenames = [NSString stringWithFormat:@"TextLabel"];
        NSLog(@"%@", filenames);

        NSString *urlString = @"http://127.0.0.1:5984/sgramimage";

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
        [request setURL:[NSURL URLWithString:urlString]];
        [request setHTTPMethod:@"POST"];

        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"application/json; 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=\"filenames\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[filenames dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\"TestEdreamzIpad.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];
        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        NSLog(@"Response : %@",returnString);
        NSLog(@"Finish");
    }

1 Answers1

2

You sending your data to the path /:dbname/:docid. As described here you have to upload the attachment in its own Content-Type:

curl -vX PUT http://127.0.0.1:5984/sgramimage?rev=:rev \
 --data-binary @TestEdreamzIpad.jpg -H "Content-Type:image/jpg"

You have to know the current revision of the doc to which the image should be attached.

Alternatively you can send attachments with a new doc in one request - binary or inline as Base64 encoded string. More about CouchDB document attachments shows the API path documentation.

Ingo Radatz
  • 1,225
  • 8
  • 9