5

I tried AFNetworking's "Create an upload task" and this to upload image in .net server, but couldn't. This is what I tried.

- (void)uploadJPEGImage:(NSString*)requestURL image:(UIImage*)image
{
    NSURL *url = [[NSURL alloc] initWithString:requestURL];
    NSMutableURLRequest *urequest = [NSMutableURLRequest requestWithURL:url];

    [urequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [urequest setHTTPShouldHandleCookies:NO];
    [urequest setTimeoutInterval:60];
    [urequest setHTTPMethod:@"POST"];

    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [urequest setValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    // add image data
    NSData *imageData = UIImageJPEGRepresentation(qrCodeImage.image, 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", pictureName] 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]];
    [urequest setHTTPBody:body];
    NSLog(@"Check response if image was uploaded after this log");
    //return and test
    NSData *returnData = [NSURLConnection sendSynchronousRequest:urequest returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    NSLog(@"%@", returnString);

}

Since AFNetworking code gives, me this run time error despite adding

self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", @"text/html", nil];

Thanks.

Community
  • 1
  • 1
Deepak Thakur
  • 3,453
  • 2
  • 37
  • 65
  • There's a line commented out in the code that adds a `Content-Disposition` line to the data. You need this when performing a multipart post, so uncomment it. – neilco Dec 10 '13 at 07:19
  • I commented that out because I have generated the QR Code in application itself and hence image will not have any path. – Deepak Thakur Dec 10 '13 at 07:21
  • You need to have that line in your multipart payload. It's critical. The `name` value in that line is the parameter name, not a file path, e.g. `image` or `photo`. – neilco Dec 10 '13 at 07:24
  • I added imageView.image instead of pictureName, but get the html response of the web page. How do I check if the image is uploaded in the mentioned url because I was expecting {"imageurl":"http://trivetts.iconnectgroup.com/uploads/TruckTrackUpload/201312100228557401.png"} in response – Deepak Thakur Dec 10 '13 at 07:29
  • That `Content-Disposition` line needs to read as `[body appendData:[@"Content-Disposition: form-data; name=\"FileUpload1\" filename=\"image.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];` – neilco Dec 10 '13 at 07:36

2 Answers2

2

Your code was missing the __VIEWSTATE content par. I've added in code to extract the URL of the uploaded image at the end:

- (void)uploadJPEGImage:(NSString*)requestURL image:(UIImage*)image
{
    NSURL *url = [[NSURL alloc] initWithString:requestURL];
    NSMutableURLRequest *urequest = [NSMutableURLRequest requestWithURL:url];

    [urequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [urequest setHTTPShouldHandleCookies:NO];
    [urequest setTimeoutInterval:60];
    [urequest setHTTPMethod:@"POST"];

    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [urequest setValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];

    // Add __VIEWSTATE
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"__VIEWSTATE\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"/wEPDwUKLTQwMjY2MDA0M2RkXtxyHItfb0ALigfUBOEHb/mYssynfUoTDJNZt/K8pDs=" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

    // add image data
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    if (imageData) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Disposition: form-data; name=\"FileUpload1\"; filename=\"image.jpg\"\r\n" 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]];

    [urequest setHTTPBody:body];
    NSLog(@"Check response if image was uploaded after this log");
    //return and test
    NSHTTPURLResponse *response = nil;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:urequest returningResponse:&response error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    NSLog(@"%@", returnString);

    // Extract the imageurl
    NSArray *parts = [returnString componentsSeparatedByString:@"\r\n"];
    if (parts.count > 0) {
        NSError *error = NULL;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[parts[0] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
        NSLog(@"%@", result[@"imageurl"]); // Will either be nil or a URL string
    }
}
neilco
  • 7,964
  • 2
  • 36
  • 41
1

1.I think you miss the hidden input in upload page:

upload page html code

2.Using the code below, i can upload successfully and get the right response string:

xcode log

UIImage *image = [UIImage imageNamed:@"a.jpg"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer new];

// add hidden parameter here
NSDictionary * parameters = @{@"__VIEWSTATE":@"/wEPDwUKLTQwMjY2MDA0M2RkXtxyHItfb0ALigfUBOEHb/mYssynfUoTDJNZt/K8pDs="};

[manager POST:@"http://cnapi.iconnectgroup.com/upload/fileuploadnew.aspx" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    // add image date here
    [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.5) name:@"FileUpload1" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];

} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSData * data = (NSData *)responseObject;
    NSLog(@"Success,Response string: %@", [NSString stringWithCString:[data bytes] encoding:NSISOLatin1StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
Joiningss
  • 1,320
  • 9
  • 14