在我的iOS应用中,我必须将图像存储在远程数据库中。我已经通过BLOB完成了。但我想通过仅存储其路径来实现它。我已经尝试了很多但是我没有编写客户端代码。
客户端代码:
NSData *imageData = UIImageJPEGRepresentation(self.imgview.image,0.2); //change Image to NSData
if (imageData != nil)
{
NSString *filenames = @"catttt.jpeg"; //set name here
NSLog(@"%@", filenames);
NSString *urlString = @"http://localhost/insertIntoImage.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"filenames\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[filenames dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpeg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@",returnString);
NSLog(@"finish");
}
远程端代码:
$target_path = "uploads/";
$target_file = $target_path . basename( $_FILES['userfile']['filenames']);
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_file)) {
echo "The file ". basename( $_FILES['userfile']['filenames']) . " has been uploaded";
} else {
echo "There was an error uploading the file, please try again!";
}
?>
答案 0 :(得分:1)
首先将图像上传到服务器,然后将图像名称/路径更新为DB
以下是将图像存储到服务器的功能
这里$ image是来自IOS APP的图像数据
$image = $_POST['image_name_from_app'];
$image = str_replace("<", "", $image);
$image = str_replace(">", "", $image);
$image = str_replace("<", "", $image);
$image = str_replace(">", "", $image);
$image = preg_replace('/[\s\W]+/', '', $image);
$bin = hex2bin($image);
$path = "user_images/";
$imageName = time() .".png";
$path = "user_images/";
if (file_put_contents($path . $imageName, $bin)) {
return $imageName;
}
return false;