0

我有一段来自 upload.php 的代码

$uploaddir = '../photo/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
{
    //...
}

如何添加一个功能,如果用户没有上传图片,则上传默认图片?

4

3 回答 3

0

您应该首先检查$_FILES['userfile']['error'] === UPLOAD_ERR_OK
它是否不是UPLOAD_ERR_OK,然后出现问题。
可以在此处找到错误列表:file-upload.errors

例子:

$uploaddir = '../photo/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if ($_FILES['userfile']['error'] === UPLOAD_ERR_OK) {
  if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    /** do stuff **/
  }
} else {
  echo "An error occurred with your upload.<br>";

  switch($_FILES['userfile']['error']) { 
    case UPLOAD_ERR_INI_SIZE: 
      echo "The uploaded file exceeds the upload_max_filesize directive in php.ini"; 
      break; 
    case UPLOAD_ERR_FORM_SIZE: 
      echo "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; 
      break; 
    case UPLOAD_ERR_PARTIAL: 
      echo "The uploaded file was only partially uploaded"; 
      break; 
    case UPLOAD_ERR_NO_FILE: 
      echo "No file was uploaded"; 
      break; 
    case UPLOAD_ERR_NO_TMP_DIR: 
      echo "Missing a temporary folder"; 
      break; 
    case UPLOAD_ERR_CANT_WRITE: 
      echo "Failed to write file to disk"; 
      break; 
    case UPLOAD_ERR_EXTENSION: 
      echo "File upload stopped by extension"; 
      break; 
    default: 
      $message = "Unknown upload error"; 
      break; 
  }
}
于 2013-07-05T19:57:20.937 回答
0

这不是我的答案。这是CodeAngry的评论:

为什么不使用默认图像 URL,这样您就不会将其上传给每个用户。因此,如果用户有图像,请显示该图像。如果他不只是使用默认的

仅存储用户明确选择上传的图像更有效。如果用户没有上传它,那么当你必须展示它时,请执行以下操作:

PHP

//assumimg you stored the image with user_id as name
$path_to_image = "img/" . $user_id . ".jpg";
$image = (file_exists($path_to_image)) ? $path_to_image : $default_image_path;

HTML

<img src="<?=$image?>" alt="" />

此外,它将为您节省磁盘空间!

于 2013-07-06T00:32:16.060 回答
0

你也可以使用它:(当然在 php 的情况下在 echo "" 下)

// Replace source with other image in case user didn't upload any photo
$('img').error(function(){
        $(this).attr('src', 'missing.png');
});

// Or, hide the 'broken image' 
$("img").error(function(){
        $(this).hide();
});
于 2015-07-28T15:23:29.610 回答