如何在用户上传任何图像时设置默认图像?

时间:2017-02-14 16:31:52

标签: php image

如果用户未上传自己的图片,如何将默认图片设置为import java.util.HashMap; import java.util.Map; public class StackOverflowQuestion { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("" + findLowestFrequency("aaabbc")); } public static char findLowestFrequency(String input) { Map<Character, Integer> map = new HashMap<Character, Integer>(); for (char c : input.toCharArray()) if (map.containsKey(c)) map.put(c, map.get(c) + 1); else map.put(c, 0); char rarest = map.keySet().iterator().next(); for (char c : map.keySet()) if (map.get(c) < map.get(rarest)) rarest = c; return rarest; } } 以使用它?

upload/'default image.jpg'

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

如评论中所述,从$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"];
}