[英]upload base64 encoded image to Mamp server
我正在使用以下方法將base64編碼格式的圖像發送到服務器
//用於上傳圖片......................
- (void)ImageUpload:(UIImage *)image
{
NSData *imageData = UIImagePNGRepresentation(image);
NSString *urlString=@"http://192.168.77.145/uploadImage.php";
NSURL *url = [NSURL URLWithString:urlString];
NSString *base64ImageString = [imageData base64EncodedStringWithOptions:kNilOptions]; // iOS 7+
base64ImageString = [base64ImageString stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
NSString *jsonReqString = [[NSString alloc] initWithFormat:@"{\"photo\":\"%@\",\"imageExtension\":\"%@\"}", base64ImageString,@"123"];
NSString *post =[[NSString alloc] initWithFormat:@"request=%@",jsonReqString];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!data)
{
NSLog(@"wifi error");
NSLog(@"sendAsynchronousRequest error: %@", connectionError);
return ;
}
else
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
}
}];
}
但是我沒有將base64字符串發送到服務器。 我的參數photo和imageextension都為空。
這是我的服務器端代碼
<?php
$base = $_POST['photo'];
echo $base;
$filename = $_POST['imageExtension'];
echo $filename;
// Decode Image
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploadedimages/'.$filename, 'wb');
// Create File
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete, Please check your php file directory';
?>
感謝幫助
問題在服務器端的第二行
您正在嘗試為關鍵“照片”獲取價值
$base = $_POST['photo'];
你需要改變那條線
$base = $_POST['request'];
之后,您需要添加以下代碼
$baseImg = json_decode($base, true);
$filename = $baseImg["imageExtension"];
$tmpImg = $baseImg["photo"];
$binary=base64_decode($tmpImg);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.