在ios中将图像文件传输到服务器

时间:2015-08-05 04:55:02

标签: ios objective-c iphone web-services

我在我的iOS应用程序上工作,我想将图像文件发送到服务器。

如何以字节格式发送图像文件。

请提出宝贵的建议。

2 个答案:

答案 0 :(得分:2)

您可以使用以下给定的功能

   -(NSString *)getStringFromImage:(UIImage *)image{
        if(image){
            NSData *dataObj = UIImagePNGRepresentation(image);
            //[appDelegate showAlert:@"Data Size" message:[NSString stringWithFormat:@"Data length = %lu",(unsigned long)dataObj.length]];
            return [dataObj base64EncodedStringWithOptions:0];
        } else {
            return @"";
        }
    }

答案 1 :(得分:1)

将您的图片转换为NSData并使用base64编码并将其添加到jsonarray

NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:[UIImageJPEGRepresentation(yourimage, 1) base64EncodedStringWithOptions:0], @"image", nil];

if([NSJSONSerialization isValidJSONObject:newDatasetInfo]){


//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:nil];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"your url"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:jsonData];


NSURLSessionConfiguration *config=[NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *session=[NSURLSession sessionWithConfiguration:config];

NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    if(response){
        NSString *resp = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
        NSLog(@"Echo %@",resp);


        });


    }
    else{
        NSLog(@"Timeout");



        });

    }



}];
[task resume];

}

稍后在服务器(php)端解码基础64,你可以保存它

 <?php
$string =  @file_get_contents('php://input');
 $json = json_decode($string, true);


    $file = 'uploads/filename';
    $file_info = new finfo(FILEINFO_MIME);
    // Extract the mime type
    $mime_type = $file_info->buffer($json['image']);
    file_put_contents($file, base64_decode($json['image']));
    echo "sucess saving image";
exit;
?>