Upload image to the PHP server from iOS

后端 未结 6 665
天涯浪人
天涯浪人 2020-11-30 22:02

I know this question has been asked earlier as well but my issue is a bit different.

I want to upload an image to the PHP server and i want to send more parameters a

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 22:28

    Using AFNetworking this is how I do it:

    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:@"myUserName" forKey:@"username"];
        [params setObject:@"1234" forKey:@"password"];
        [[AFHTTPRequestOperationLogger sharedLogger] startLogging];
        NSData *imageData;
        NSString *urlStr = [NSString stringWithFormat:@"http://www.url.com"];
        NSURL *url = [NSURL URLWithString:urlStr];
    
        AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
           imageData = UIImageJPEGRepresentation(mediaFile, 0.5);
    
    
        NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:nil parameters:params constructingBodyWithBlock: ^(id formData)
        {
                  [formData appendPartWithFileData:imageData name:@"mediaFile" fileName:@"picture.png" mimeType:@"image/png"];
        }];
    
        AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
    
        success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
        {
    
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"File was uploaded" message:@""
                                                           delegate:self cancelButtonTitle:@"Close" otherButtonTitles: nil];
            [alert show];
        }
        failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON)
        {
            NSLog(@"request: %@",request);
            NSLog(@"Failed: %@",[error localizedDescription]);
        }];
    
    
        [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite)
        {
            NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
        }];
        [httpClient enqueueHTTPRequestOperation:operation];
    

提交回复
热议问题