[英]Why I lost the filename value when I click the submit button
I have made a form to pass xml files on a server. 我已经制作了一种在服务器上传递xml文件的表格。 Although when it correctly sends the file to the server, it seems that the pages reloads and the value of the file name is lost and my javascript code returns nothing. 尽管当它正确地将文件发送到服务器时,似乎页面已重新加载并且文件名的值丢失了,并且我的JavaScript代码什么也不返回。 However if I remove the line 但是,如果我删除行
<input type="submit" />
from the code below it keeps the filename in the variable x but it doesn't send the file to the server. 从下面的代码中,它将文件名保留在变量x中,但不会将文件发送到服务器。 I want to send the file on the server and keep its name into a variable in order to use in any other javascript functions. 我想在服务器上发送文件,并将其名称保留为变量,以便在其他任何javascript函数中使用。
<?php
$uploads_dir='/web/stud/external/scomvs2/epicurus';
if(isset($_FILES['xml_file1'])){
$errors= array();
$file_name = $_FILES['xml_file1']['name'];
$file_size =$_FILES['xml_file1']['size'];
$file_tmp =$_FILES['xml_file1']['tmp_name'];
$file_type=$_FILES['xml_file1']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['xml_file1']['name'])));
$expensions= array("xml","XML");
if(in_array($file_ext,$expensions)== false){
$errors[]="extension not allowed, please choose an xml file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"$uploads_dir/$file_name");
echo "Success";
}else{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" id="uploading" name="xml_file1"/>
<input type="submit" />
</form>
<button type="button" onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("uploading").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
You can add in our Javascript part the following: 您可以在Javascript部分中添加以下内容:
<script>
function myFunction() {
var x = <?=json_encode($file_name)?>;
document.getElementById("demo").textContent = x;
}
</script>
Now when in Javascript you call that function, the demo element will show the file name. 现在,当您使用Javascript调用该函数时, demo元素将显示文件名。 Note that it is better to use textContent instead of innerHTML , although with filenames you don't risk to have special characters that HTML would interpret ( <>&
). 请注意,最好使用textContent而不是innerHTML ,尽管使用文件名时,您不必冒用 HTML可以解释的特殊字符( <>&
)的风险。
Now you should also make sure that $file_name is always defined. 现在,您还应该确保始终定义$ file_name 。 So at the top of your PHP code, add: 因此,在您的PHP代码的顶部,添加:
$file_name = '';
Instead of injecting the file name in your Javascript code, you could also let it be injected directly in the demo tag, like this: 除了将文件名注入您的Javascript代码中之外,您还可以将其直接注入到demo标记中,如下所示:
<p id="demo"><?=htmlspecialchars($file_name)?></p>
Then you don't need Javascript to fill it in, if that is all you wanted to do. 然后,如果您只是想这样做,则不需要Javascript来填写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.