0

I used this code to upload an image file to php server. but it doesn't work,actually it even doesn't trigger the php program. What is wrong with this code. By the way,can anybody recommend me some websites which has some tutorials about http format? I really don't understand the body of the URL request.enter code here

-(void)uploadTesting:(UIImage*)image

{

    NSData *imageData = UIImageJPEGRepresentation(image, 0.9);
    NSString *urlString = @"http://localhost/ColorPicker/api.upload.php";


    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];

    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSString *imgName =@"test image";
    NSLog(@"image name : %@",imgName);

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"files\"; filename=\"%@\"\r\n", imgName]] 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];
    NSLog(@"setRequest : %@", request);


    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    NSLog(@"returnstring is : %@",returnString);

}
user3788871
  • 25
  • 3
  • 10

0 Answers0