【问题标题】:User uploads image to server and image is set to background-image of div用户上传图片到服务器,图片设置为 div 的背景图片
【发布时间】:2018-10-14 07:31:57
【问题描述】:

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

我已经搞砸了这样一个简单的脚本,但是当按下提交时页面当然会改变。我需要它留在 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.";
    }
}
?>

【问题讨论】:

  • 仅供参考,我不能做本地的原因是因为我稍后将使用画布保存图像,而本地似乎无法使用它。

标签: html ajax image background upload


【解决方案1】:

不幸的是,安全地执行此操作并不是simple 的全部。上传后嵌入图像的最简单方法是将其作为内联 base64 提供(它比通过 url 提供更多内存和带宽,但你想要它simple,base64 方法避免了像 html 编码最终的问题保存名称,确保 Web 服务器对上传文件夹具有权限,以及无法从 Web 根文件夹访问保存文件夹的问题)。根据经验,您不应让黑客决定您服务器上的实际保存文件名(如果黑客将文件名设为../../../../../etc/passwd\x00.jpg/srv/http/default/evil_script.php\x00.jpg&lt;script&gt;evil_javascript();&lt;/script&gt;.jpg 会发生什么?),但既然你想要它@ 987654326@,您可以验证名称不包含任何危险字符(正则表达式在这里派上用场),替代方法是将用户(/hacker-supplied?)文件名保存在数据库中,然后打开-其他名称下的磁盘文件(也许将磁盘上的文件名设置为元数据数据库的此文件的唯一键?这是我通常做的,但那不是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>

【讨论】:

    猜你喜欢
    • 2013-04-25
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    相关资源
    最近更新 更多