在单个帖子请求中上传图像和一些其他参数

时间:2013-11-02 12:01:39

标签: ios iphone

我正在尝试上传图片和一些文字。我能够发布文本,但不知何故图像无法到达服务器。

以下是我的代码:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *password = [[Utilities sharedConfiguration] sha1:txtPassword.text];
        NSString *post = [NSString stringWithFormat:@"id_sender=%@&token=%@&array_receiver=%@&message=%@&time_allowed=%@&password=%@",[defaults objectForKey:@"id_user"],[defaults objectForKey:@"token"],selectedContact,txtMessage.text,txtTime.text,password];
        NSLog(@"post %@",post);
        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        NSMutableData *data = [NSMutableData dataWithData:postData];
        //NSMutableData *data = nil;
        if(myimage!=nil){
            NSString *boundary = @"---------------------------14737809831466499882746641449";
            [data appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [data appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filetype=\"image/png\"; filename=\"image.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
            [data appendData:[[NSString stringWithFormat:@"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
            [data appendData:[NSData dataWithData:UIImagePNGRepresentation(myimage)]];
        }
        NSString *postLength = [NSString stringWithFormat:@"%d", [data length]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:@"https://www.myurl.com/send_message_17294.php"]];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:data];

        [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
        [NSURLConnection connectionWithRequest:request delegate:self];

2 个答案:

答案 0 :(得分:2)

您可以使用AFNetworking,因此您无需深入了解多部分请求格式。

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://hostport"]];
NSDictionary *simpleParams = @{ @"key": @"value" };
NSMutableURLRequest* request = [client multipartFormRequestWithMethod:@"POST" path:@"/path" parameters: simpleParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        [formData appendPartWithFileData:fileData
                                    name:@"paramName"
                                fileName:@"filename.png"
                                mimeType:@"image/png"];
    }];

然后根据预期的响应创建一个操作。例如,如果您期望JSON:

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

    // handle success

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {

    // handle error

}];

您可以在AFNetworking documentation

中获取更多信息

答案 1 :(得分:-1)

试试这个:它是一个同步请求。图片采用 base64 字符串格式

    NSString * param = [NSString stringWithFormat:@"%@=%@&%@=%@&%@=%@",
                                @"uphoto",imageData, @"category",categoryName, @"name",FIRSTNAME]; // parameters

    NSData *postData = [param dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://www. ..."];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    [req setHTTPMethod:@"POST"];
    [req setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"];
    [req setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [req setHTTPBody:postData];

    NSError *error = nil;
    NSHTTPURLResponse *res = nil;

    NSData *responceData = [NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&error];
    if (error)
    {
        //handle error        
        return nil;
    }
    else
    {

    }