Html 用户将图像上传到服务器,图像设置为div的背景图像

Html 用户将图像上传到服务器,图像设置为div的背景图像,html,ajax,image,background,upload,Html,Ajax,Image,Background,Upload,我在寻找一个超级简单的方法,允许用户上传一个图像到我的服务器,然后将上传的图像设置为div的背景图像标签。我不能使用只显示本地文件的方法,它需要实际上传到我的服务器 我已经弄乱了这样一个简单的脚本,但是当按下submit时页面当然会改变。我需要它停留在html页面上,并改变div。任何帮助感谢 <!DOCTYPE html> <html> <body> <form action="winupload.php" method="post" enc

我在寻找一个超级简单的方法,允许用户上传一个图像到我的服务器,然后将上传的图像设置为div的背景图像标签。我不能使用只显示本地文件的方法,它需要实际上传到我的服务器

我已经弄乱了这样一个简单的脚本,但是当按下submit时页面当然会改变。我需要它停留在html页面上,并改变div。任何帮助感谢

    <!DOCTYPE html>
<html>
<body>

<form action="winupload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

<div id="mainimage" style="background-color:#cccccc;width:300px;height:300px;">test</div>

</body>
</html>

选择要上载的图像:
测试
上面是HTML,下面是PHP

    <?php
$target_dir = "winups/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

// Check if file already exists
//if (file_exists($target_file)) {
//    echo "Sorry, file already exists.";
//    $uploadOk = 0;
//}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        $changable_data["js_script"] = 'document.getElementById("mainimage").style.backgroundImage = "url('. basename( $_FILES["fileToUpload"]["name"]). ')";';
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

不幸的是,安全地执行此操作并不是那么简单。上传后嵌入图像的最简单方法是将其作为内联base64(它使用的ram和带宽比通过url提供的要多,但您希望它
简单
,base64方法避免了诸如html编码最终存储名、确保web服务器具有上载文件夹的权限以及无法从web根文件夹访问存储文件夹等问题)。根据经验,您不应该让黑客决定服务器上的实际保存文件名(如果黑客将文件名设置为
。/../../../../../../etc/passwd\x00.jpg
?或
/srv/http/default/evil_script.php\x00.jpg
evil_javascript();.jpg
?),但由于您希望它
简单
,因此可以验证名称是否不包含任何危险字符(这里可以使用regex),另一种方法是将用户(/hacker提供的?)文件名保存在数据库中,并将磁盘上的文件保存在其他名称下(可能将磁盘上的文件名设置为元数据数据库对此文件的唯一键?这是我通常做的,但这并不简单)。至于
我需要它停留在html页面上并更改div
-这不需要通过javascript刷新即可实现,但不是必需的,而且
更简单,您可以使用普通的旧动态php页面,而不是此处的javascript/XMLHttpRequest路径,请尝试:

<?php
declare(strict_types = 1);
$uploadOk = 0;
if (! empty ( $_FILES ['fileToUpload'] )) {
    $target_dir = "winups/";
    $name = $_FILES ['fileToUpload'] ['name'];
    if (! preg_match ( '/^[[:alnum:][:space:]\_\.\-]{4,100}$/ui', $name )) {
        http_response_code ( 400 );
        die ( "illegal filename detected. for security reasons, the filename must match the regex /^[[:alnum:][:space:]\_\.\-]{4,100}$/ui" );
    }
    $imageFileType = strtolower ( pathinfo ( $name, PATHINFO_EXTENSION ) );
    $extensionWhitelist = array (
            'jpg',
            'jpeg',
            'png',
            'gif',
            'bmp' 
    );
    if (! in_array ( $imageFileType, $extensionWhitelist, true )) {
        http_response_code ( 400 );
        die ( "Sorry, only allowed image types are: " . htmlentities ( implode ( ', ', $extensionWhitelist ) ) );
    }
    if (false === getimagesize ( $_FILES ["fileToUpload"] ["tmp_name"] )) {
        http_response_code ( 400 );
        die ( "image is corrupted" );
    }
    // ok, the image passed the security checks.

    $target_file = $target_dir . $name;
    // now to find an unique filename
    // OPTIMIZEME, excessive syscalls will be cpu-expensive and slow, DoS vector, use glob() or some limit lower than PHP_INT_MAX ? 
    if (file_exists ( $target_file )) {
        $success = false;
        for($i = 2; $i < PHP_INT_MAX; ++ $i) {
            if (! file_exists ( "$i." . $target_file )) {
                $success = true;
                $target_file = "$i." . $target_file;
                break;
            }
        }
        if (! $success) {
            http_response_code ( 500 );
            die ( "too many duplicates of this filename! (" . PHP_INT_MAX . " duplicates!)" );
        }
    }
    $uploadOk = 1;

    if (! move_uploaded_file ( $_FILES ["fileToUpload"] ["tmp_name"], $target_file )) {
        http_response_code ( 500 );
        die ( "Sorry, an internal server error while saving your file" );
    }
}
?>
<!DOCTYPE html>
<html>
<body>

    <form action="?" method="post" enctype="multipart/form-data">
        Select image to upload: <input type="file" name="fileToUpload"
            id="fileToUpload"> <input type="submit" value="Upload Image"
            name="submit">
    </form>
<?php
if ($uploadOk) {
    echo "The file " . htmlentities ( $name ) . " has been uploaded.";
    echo '<div id="mainimage" style="background-color: #cccccc; width: 300px; height: 300px;"><img src="data:image/' . $imageFileType . ';base64,' . base64_encode ( file_get_contents ( $target_file ) ) . '" /></div>';
}
?>
</body>
</html>

选择要上载的图像:

仅供参考,我不能使用local的原因是我以后将使用canvas保存图像,而local似乎无法使用它。