[英]Uploading image file on the same page
I am trying to upload a image file on the same page using PHP and javascript.I have embedded javascript code inside PHP to show some messages and image inside html tags. 我正在尝试使用PHP和javascript在同一页面上上传图像文件。我已经在PHP中嵌入了javascript代码以在html标签中显示一些消息和图像。 Below is my code, please point me out what have done wrong and get it corrected.
以下是我的代码,请指出错误的地方并予以纠正。 Any help would be appreciated.
任何帮助,将不胜感激。 Thanks..
谢谢..
ImageUpload.php ImageUpload.php
if( isset($_POST['submit']) ) {
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$maxFileSize = 200000;
$fileExt = explode(".", $fileName);
$currFileExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png', 'gif');
if(in_array($currFileExt, $allowed) ){
if($fileSize < $maxFileSize) {
if($fileError == 0){
$uniqueFileName = uniqid('',true).".".$currFileExt;
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$uniqueFileName);
?>
<script type="text/javascript">
document.getElementById('image').setAttribute("src",<?= 'uploads/'.$uniqueFileName; ?>);
</script>
<?php
} else {
?>
<script type="text/javascript">
document.getElementById('imageHolder').innerHTML = "There is an error in uploading file";
</script>
<?php
}
} else {
?>
<script type="text/javascript">
document.getElementById('imageHolder').innerHTML = "fileSize should be atmost 500kb";
</script>
<?php
}
} else {
?>
<script type="text/javascript">
document.getElementById('imageHolder').innerHTML = "This type of file is not allowed";
</script>
<?php
}
}
?>
<!DOCTYPE>
<html lang="en">
<body>
<form action="<?= htmlspecialchars($_SERVER['PHP_SELF']); ?>"
method="post" enctype="multipart/form-data" id="form" >
<input type="file" name="file" id="file" />
<input type="submit" value="Upload Image" name="submit" id="submit" />
</form>
<p ><h2>Upload image here</h2></p>
<div id="imageHolder" style="height:200px;max-height:200px;max-
width:200px;width:200px;border:1px solid black;">
<img src="" id="image" style="height: 200px;width: 200px;"/>
</div>
</body>
</html>
To resolve your problem see @u_mulder answer but using javascript in this state is't good way, i recommend you change your code like this 要解决您的问题,请参见@u_mulder答案,但是在这种状态下使用javascript并不是一种好方法,我建议您像这样更改代码
<?php
$error = ''; // add $error to hold error text
$image_url = ''; // add $image_url to hold image url
if( isset($_POST['submit']) ) {
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$maxFileSize = 200000;
$fileExt = explode(".", $fileName);
$currFileExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png', 'gif');
if(in_array($currFileExt, $allowed) ){
if($fileSize < $maxFileSize) {
if($fileError == 0){
$uniqueFileName = uniqid('',true).".".$currFileExt;
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$uniqueFileName);
//this part updated
$image_url = 'uploads/'.$uniqueFileName;
} else {
// this part updated
$error = 'There is an error in uploading file';
}
} else {
// this part updated
$error = "fileSize should be atmost 500kb";
}
} else {
// this part updated
$error = "This type of file is not allowed";
}
}
?>
<!DOCTYPE>
<html lang="en">
<body>
<form action="<?= htmlspecialchars($_SERVER['PHP_SELF']); ?>"
method="post" enctype="multipart/form-data" id="form" >
<input type="file" name="file" id="file" />
<input type="submit" value="Upload Image" name="submit" id="submit" />
</form>
<p ><h2>Upload image here</h2></p>
<div id="imageHolder" style="height:200px;max-height:200px;max-
width:200px;width:200px;border:1px solid black;">
<?php
//this part updated
if($error):
?>
<p><?php echo $error; ?></p>
<?php
endif;?>
<?php
if($image_url): ?>
<img src="<?php echo $image_url; ?>" id="image" style="height: 200px;width: 200px;"/>
<?php
endif; ?>
</div>
</body>
</html>
Your problem here is that your javascript code runs before required html element appears on the page. 您的问题是您的JavaScript代码在页面上所需的html元素出现之前就已运行 。 So, when you try to get element with
因此,当您尝试使用
document.getElementById('imageHolder')
whereas this element not renedered, javascript founds nothing and returns null
. 而未重新定义此元素的内容,javascript则未找到任何内容,并返回
null
。
So, you need to output javascript codes after required elements are outputted. 因此,您需要在输出必需的元素之后输出javascript代码。
You can do for example like this: 您可以这样做,例如:
<!DOCTYPE>
<html lang="en">
<body>
<form action="<?= htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" enctype="multipart/form-data" id="form">
<input type="file" name="file" id="file" />
<input type="submit" value="Upload Image" name="submit" id="submit" />
</form>
<p ><h2>Upload image here</h2></p>
<div id="imageHolder" style="height:200px;max-height:200px;max-
width:200px;width:200px;border:1px solid black;">
<img src="" id="image" style="height: 200px;width: 200px;"/>
</div>
<?php
if( isset($_POST['submit']) ) {
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$maxFileSize = 200000;
$fileExt = explode(".", $fileName);
$currFileExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png', 'gif');
if(in_array($currFileExt, $allowed) ){
if($fileSize < $maxFileSize) {
if($fileError == 0){
$uniqueFileName = uniqid('',true).".".$currFileExt;
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$uniqueFileName);?>
<script type="text/javascript">
document.getElementById('image').setAttribute("src",<?= 'uploads/'.$uniqueFileName; ?>);
</script>
<?php
} else {?>
<script type="text/javascript">
document.getElementById('imageHolder').innerHTML = "There is an error in uploading file";
</script>
<?php
}
} else {?>
<script type="text/javascript">
document.getElementById('imageHolder').innerHTML = "fileSize should be atmost 500kb";
</script>
<?php }
} else {?>
<script type="text/javascript">
document.getElementById('imageHolder').innerHTML = "This type of file is not allowed";
</script>
<?php
}
}?>
</body>
</html>
In this case html elements are in DOM already and javascript can find them. 在这种情况下,html元素已经在DOM中,而javascript可以找到它们。
Another option can be using jquery
with document.ready
(or pure js-analog load
function, afair), in this case you can place your js-codes where you want. 另一种选择是将
jquery
与document.ready
配合使用(或纯js模拟load
函数,不公平),在这种情况下,您可以将js代码放在所需的位置。
<table width="80%" border="0">
<tr>
<th onmousedown="fileUpload_upd(document.getElementById('myform_upd'),'upload_upd.php?path=img/my_image.jpg','upload1'); return false;">
Send
</th>
</tr>
</table>
and file upload_upd.php : 和文件upload_upd.php:
$img_ath=$_GET["path"];
$upl=move_uploaded_file($_FILES["datafile_upd"]["tmp_name"],$img_ath);
?> ?>
and fileUpload_upd in javascript file : 和fileUpload_upd在javascript文件中:
function fileUpload_upd(form, action_url, div_id) {
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "upload_iframe");
iframe.setAttribute("name", "upload_iframe");
iframe.setAttribute("width", "0");
iframe.setAttribute("height", "0");
iframe.setAttribute("border", "0");
iframe.setAttribute("style", "width: 0; height: 0; border: none;");
// Add to document...
form.parentNode.appendChild(iframe);
window.frames['upload_iframe'].name = "upload_iframe";
iframeId = document.getElementById("upload_iframe");
// Add event...
var eventHandler = function () {
if (iframeId.detachEvent) iframeId.detachEvent("onload", eventHandler);
else iframeId.removeEventListener("load", eventHandler, false);
// Message from server...
if (iframeId.contentDocument) {
content = iframeId.contentDocument.body.innerHTML;
} else if (iframeId.contentWindow) {
content = iframeId.contentWindow.document.body.innerHTML;
} else if (iframeId.document) {
content = iframeId.document.body.innerHTML;
}
document.getElementById(div_id).innerHTML = content;
// Del the iframe...
setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
}
if (iframeId.addEventListener) iframeId.addEventListener("load", eventHandler, true);
if (iframeId.attachEvent) iframeId.attachEvent("onload", eventHandler);
// Set properties of form...
form.setAttribute("target", "upload_iframe");
form.setAttribute("action", action_url);
form.setAttribute("method", "post");
form.setAttribute("enctype", "multipart/form-data");
form.setAttribute("encoding", "multipart/form-data");
// Submit the form...
form.submit();
document.getElementById(div_id).innerHTML = "</br></br></br><img src=src/img/loadingsmall.gif></br></br></br>";
}
Hello I have changed your code a little bit. 您好,我对您的代码做了一些更改。 I put your HTML part before the script
我将您的HTML部分放在脚本之前
<!DOCTYPE>
<html lang="en">
<body>
<form action="<?= htmlspecialchars($_SERVER['PHP_SELF']); ?>"
method="post" enctype="multipart/form-data" id="form" >
<input type="file" name="file" id="file" />
<input type="submit" value="Upload Image" name="submit" id="submit" />
</form>
<p ><h2>Upload image here</h2></p>
<div id="imageHolder" style="height:200px;max-height:200px;max-
width:200px;width:200px;border:1px solid black;">
<img src="" id="image" style="height: 200px;width: 200px;"/>
</div>
</body>
</html>
<?php
if(isset($_POST['submit']) ) {
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$maxFileSize = 200000;
$fileExt = explode(".", $fileName);
$currFileExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png', 'gif');
if(in_array($currFileExt, $allowed) ){
if($fileSize < $maxFileSize) {
if($fileError == 0){
$uniqueFileName = uniqid('',true).".".$currFileExt;
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$uniqueFileName);
?>
<script type="text/javascript">
document.getElementById('image').setAttribute("src","<?php echo 'uploads/'.$uniqueFileName; ?>");
</script>
<?php
} else {
?>
<script type="text/javascript">
document.getElementById('imageHolder').innerHTML = "There is an error in uploading file";
</script>
<?php
}
} else {
?>
<script type="text/javascript">
document.getElementById('imageHolder').innerHTML = "fileSize should be atmost 500kb";
</script>
<?php
}
} else {
?>
<script type="text/javascript">
document.getElementById('imageHolder').innerHTML = "This type of file is not allowed";
</script>
<?php
}
}
?>
and I changed your code this 我改变了你的代码
<script type="text/javascript">
document.getElementById('image').setAttribute("src",<?= 'uploads/'.$uniqueFileName; ?>);
</script>
to this 对此
<script type="text/javascript">
document.getElementById('image').setAttribute("src","<?php echo 'uploads/'.$uniqueFileName; ?>");
</script>
Now, I am not getting any error in console as you mentioned. 现在,您没有提到控制台中出现任何错误。 Please try the code
请尝试代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.