1

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

以下是我的代码:

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];
4

2 回答 2

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 文档中获得更多信息。

于 2013-11-02T13:03:42.383 回答
-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
    {

    }
于 2013-11-02T12:15:46.717 回答