【发布时间】: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