Base64 Over HTTP POST 丢失数据 (Objective-C)
2022-08-30 21:47:21
我目前有一个HTTP POST请求和一个Base64编码库,我将图像编码到B64,然后通过POST方法通过HTTP发送。
我将Base64输出到XCodes控制台,复制并粘贴它,它完美地工作。尽管我存储在数据库中的Base64(MongoDB,纯文本文件等)总是在另一端损坏。
工作版本(从XCode复制和粘贴):http://dontpanicrabbit.com/api/working.php 损坏的版本(来自MongoDB数据库):http://dontpanicrabbit.com/api/grabimage.php
如果您查看源代码,您会注意到它们是相同的,但是在损坏的版本中添加了空格。
我使用的 Objective-C 代码是:
MyImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(MyImage.image, 0);
[Base64 initialize];
NSString *encoded = [Base64 encode:imageData];
NSString *urlPOST = encoded;
//NSLog(@"%@",encoded);
NSString *varyingString1 = @"picture=";
NSString *varyingString2 = urlPOST;
NSString *post = [NSString stringWithFormat: @"%@%@", varyingString1, varyingString2];
NSLog(@"%@", post);
//NSString *post = @"image=%@",urlPOST;
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"url/api/insertimage.php"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
NSString *strResult = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
PHP -> MongoDB Storage
<?php
try {
// open connection to MongoDB server
$conn = new Mongo('localhost');
// access database
$db = $conn->dablia;
// access collection
$collection = $db->images;
// insert a new document
$item = array(
'picture' => $_POST['picture']
);
$collection->insert($item);
echo 'Inserted document with ID: ' . $item['_id'];
// disconnect from server
$conn->close();
} catch (MongoConnectionException $e) {
die('Error connecting to MongoDB server');
} catch (MongoException $e) {
die('Error: ' . $e->getMessage());
}
?>
输出代码:
<?php
try {
// open connection to MongoDB server
$conn = new Mongo('localhost');
// access database
$db = $conn->dablia;
// access collection
$collection = $db->images;
// execute query
// retrieve all documents
$cursor = $collection->find();
// iterate through the result set
// print each document
foreach ($cursor as $obj) {
echo '<img src="data:image/jpeg;base64,'.trim($obj['picture']).'">';
}
// disconnect from server
$conn->close();
} catch (MongoConnectionException $e) {
die('Error connecting to MongoDB server');
} catch (MongoException $e) {
die('Error: ' . $e->getMessage());
}
?>
我不知道为什么我似乎在POST上腐败?