【问题标题】:How do i set a default image when the user doesn`t upload any image?当用户不上传任何图像时,如何设置默认图像?
【发布时间】:2017-02-15 03:23:26
【问题描述】:

当用户不上传自己的图片时,如何将默认图片设置为upload/'default image.jpg' 以使用它?

$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);

move_uploaded_file($_FILES["image"]["tmp_name"],"upload/" . $_FILES["image"]["name"]);          
$location = "upload/" . $_FILES["image"]["name"];

【问题讨论】:

  • 首先检查$_FILES['image'] 中是否存在任何文件。如果没有,请跳过此脚本的其余部分并将$location 设置为默认值
  • 我尝试更改 $location="upload/" 。 $_FILES["图像"]["名称"];进入 $location="upload/default.jpg" 。 $_FILES["图像"]["名称"];但是当我上传照片时,它不会显示我上传的图像
  • 如果没有上传图片,不要使用$_FILES。那是仅用于上传的文件
  • 一些解释什么时候需要默认图片
  • 好吧,看来OP放弃了……

标签: php image


【解决方案1】:

在尝试使用之前,您应该首先检查是否有文件上传。

// Here's the default value
$location = "upload/default_image.jpg";

// Check if we got an uploaded file
if (!empty($_FILES['image']['tmp_name'])) {
    // We have an uploaded file, now let's handle it
    $image      = addslashes(file_get_contents($_FILES['image']['tmp_name']));
    $image_name = addslashes($_FILES['image']['name']);
    $image_size = getimagesize($_FILES['image']['tmp_name']);

    if (move_uploaded_file($_FILES["image"]["tmp_name"], "upload/" . $_FILES["image"]["name"]) {
        // Yay! It worked! Let's overwrite our default value!
        $location = "upload/" . $_FILES["image"]["name"];
    }
}

// The rest of your code

【讨论】:

    【解决方案2】:

    如 cmets 中所述,以 $location 变量中的默认文件名开头,并在需要时覆盖它

    $location = "upload/default image.jpg"; // the default file value
    $image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
    $image_name= addslashes($_FILES['image']['name']);
    $image_size= getimagesize($_FILES['image']['tmp_name']);
    
    if (move_uploaded_file($_FILES["image"]["tmp_name"],"upload/" . $_FILES["image"]["name"]) 
    {          
        // only change the location if something was uploaded
        $location="upload/" . $_FILES["image"]["name"];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-13
      • 1970-01-01
      • 1970-01-01
      • 2018-09-05
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多