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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用户将图像上传到服务器,图像设置为div的背景图像相关的知识,希望对你有一定的参考价值。

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

我已经弄乱了这样一个简单的脚本,但当按下提交时页面会发生变化。我需要它留在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 Above和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.";
    }
}
?>
答案

不幸的是,这样安全地做到这一点并不是所有simple。在上传后嵌入图像的最简单方法是将其作为内联base64(它使用更多ram和带宽而不是通过url提供它,但你想要它simple,并且base64方法避免了像html编码最终savename的问题,确保Web服务器具有上载文件夹的权限,并且无法从Web根文件夹访问保存文件夹的问题。根据经验,你不应该让黑客决定你的服务器上的实际保存文件名(如果黑客制作文件名../../../../../etc/passwdx00.jpg?或/srv/http/default/evil_script.phpx00.jpg?或<script>evil_javascript();</script>.jpg会怎么样?),但是因为你想要它simple,你可以逃脱验证该名称不包含任何危险字符(正则表达式在这里派上用场),另一种方法是将用户(/ hacker提供的?)文件名保存在数据库中,并将磁盘上的文件保存在其他名称下(也许将磁盘上的文件名设置为此文件的元数据db的唯一键?这就是我通常所做的,但这不是simple)。至于I need it stay on the html page and change the div - 这可能没有通过javascript刷新,但没有必要,更少simple,你可以用一个普通的旧动态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>

以上是关于用户将图像上传到服务器,图像设置为div的背景图像的主要内容,如果未能解决你的问题,请参考以下文章

将 DIV 设置为背景图像的大小

将 SVG 组件作为背景图像反应到 div

将 div 的大小设置为其背景图像

javascript - 有没有办法在不刷新页面的情况下在 div 上上传和预览图像(替换背景图像)?

在 nextjs 中将背景图像设置为 div 不起作用

我正在尝试使用 php 和 jquery.php 变量更改 div 的背景图像,但未获取值