我有一段来自upload.php的代码
$uploaddir = '../photo/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
{
//...
}
如何添加一个功能,如果用户没有上传图像,则会上传默认图像?
答案 0 :(得分: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;
}
}
答案 1 :(得分:0)
这不是我的答案。这是CodeAngry的评论:
为什么不使用默认图片网址,因此您不会将其上传到每个用户。因此,如果用户有图像,请显示该图像。如果他不只是使用默认的
仅存储用户明确选择上传的图像效率更高。如果用户没有上传它,那么当您必须显示它时,请执行以下操作:
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="" />
另外它会节省你的磁盘空间!
答案 2 :(得分:0)
您也可以使用它: (当然在php的情况下回声“”)
// 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();
});