将图像文件上传到服务器,在MySQL DB中存储名称

时间:2018-02-09 11:25:43

标签: php

我尝试创建文件上传时,我的当前脚本似乎无法工作,因为我认为应该这样做。

我已经设法将保存在MySQL表格中的数据保存好了,但我似乎无法将文件存入“上传”状态。 ?目录

if(isset($_POST['new']) && $_POST['new']==1){

    $folder = "uploads/";
    $upload_image = $folder . basename($_FILES["image1"]["name"]);
    move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $upload_image);


    $trn_date = date("Y-m-d H:i:s");
    $brand =$_REQUEST['brand'];
    $user =$_SESSION["username"];
    $model = $_REQUEST['model'];
    $serial =$_REQUEST['serial'];
    $purchasedate = $_REQUEST['purchasedate'];
    $img1 =$_REQUEST['image1'];
    $ins_query="insert into table
    (`user`,`trn_date`,`brand`,`model`,`serial`,`purchasedate`,`image1`)values
    ('$user','$trn_date','$brand','$model','$serial','$purchasedate','$img1')";
    mysqli_query($con,$ins_query)
    or die(mysql_error());
    $status = "added successfully.
    </br></br><a href='home.php'>home</a>";
}

3 个答案:

答案 0 :(得分:1)

$upload_image = $folder . basename($_FILES["image1"]["name"]);
move_uploaded_file($_FILES["image1"]["tmp_name"], $upload_image);

答案 1 :(得分:0)

如果直接尝试doc所说的话,该怎么办?

$uploads_dir = '/uploads';//try over 'uploads' too or create a 'uploads' folder in you app_root
foreach ($_FILES["image1"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["image1"]["tmp_name"][$key];
        $name = $_FILES["image1"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}

答案 2 :(得分:-1)

可能Link

我在您的代码中发现了一个问题。

$folder = "uploads/";
$upload_image = $folder . basename($_FILES["image1"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $upload_image);

在这种情况下,文件没有扩展名

$folder = "uploads/";
$ext = explode('.', basename( $_FILES['image1']['name']));
$upload_image = $folder . basename($_FILES["image1"]["name"].$ext);
move_uploaded_file($_FILES["image1"]["tmp_name"], $upload_image);

uploads文件夹与php脚本位于同一目录中?

您还可以在执行以下测试时验证文件是否已正确移动

if (file_exists($upload_image)){
echo "true";
}
  

在上传到服务器之前提供文件上传验证,这将防止服务器出现恶意文件

如何在php中提供文件验证:Link