如何在将图像保存到php中的服务器中同时在数据库中硬编码文件名?

问题描述 投票:0回答:2

我正在努力从数据库中获取图像,我一直在从服务器上将其另存为url,并将其保存在服务器上。表单上有此上载图像部分,该部分将图像保存在服务器上,其url被保存在数据库中。

这里是代码:

$fileName = "";
$target_dir="/home/web/newsletter/uploads/";
$target_file_cv = $target_dir . basename($_FILES['fileToUpload']['name']);
 if(!empty($_FILES['fileToUpload']['name']))
       {
           if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file_cv)) {
               $fileName= $target_file_cv;


        } else {
            echo $twig->render("App/error.twig");
        }
    }
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO dbo.form (photo) VALUES (:fileToUpload)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':fileToUpload', $fileName);
if ($stmt->execute()) {
           $conn->commit();
 return true;
       } else {
 return false;
    }        
 ?>     

这里,我想在文件名进入数据库之前对其进行编辑。像现在一样,它另存为“ /home/web/newsletter/uploads/pic.jpg”,但我希望将其另存为“ newsletter / uploads / pic.jpg”。

我在这里提到了几个问题,并使所有其他功能正常工作,但在这里只是硬编码文件名而已。任何帮助,将不胜感激。 TIA

php sql-server image filenames
2个回答
0
投票
$fileName = implode(array_slice(explode("/",$target_file_cv),3),"/");

0
投票

好吧,我明白了:将代码更改为:

$fileName = "";
$target_dir="/home/web/newsletter/uploads/";
$target_file_cv = $target_dir . basename($_FILES['fileToUpload']['name']);
if(!empty($_FILES['fileToUpload']['name']))
   {
       if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file_cv)) {
           $fileName= "newsletter/uploads/" . $_FILES['fileToUpload']['name'];


    } else {
        echo $twig->render("App/error.twig");
    }
}
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO dbo.form (photo) VALUES (:fileToUpload)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':fileToUpload', $fileName);
if ($stmt->execute()) {
       $conn->commit();
return true;
   } else {
return false;
}        
?>     
© www.soinside.com 2019 - 2024. All rights reserved.