我尝试将浏览按钮和提交按钮组合在一起。单击按钮后,我可以选择文件。
但是文件没有上传
这是表格
HTML:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>" method="post" id="myform" enctype="multipart/form-data">
<input type="file" name="upload" id="upload" style="display:none">
<button id="browse">Upload</button>
</form>
JQuery
$(document).ready(function(){
$("#upload").change(function(){
$("#myform").submit();
});
$("#browse").click(function(){
$("#upload").click();
});
});
然后我提交了数据
PHP:
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$file=$_FILES["upload"]["name"];
$folder='uploads/';
$err=$_FILES["upload"]["error"];
$target=$folder.$file;
$temp=$_FILES["upload"]["tmp_name"];
echo $err;
move_uploaded_file($temp, $target);
}
我得到的输出是4。这意味着没有上传任何文件。如何解决此问题?
有一种简单而优雅的方法可以实现这一点。
- 将type="submit"添加到按钮中,因为并非所有web浏览器都使用"submit(提交)"作为默认按钮类型
- 添加在引发"提交"事件时触发的表单事件侦听器
示例代码:
$(document).ready(function(){
$('#myform').submit(function(e) {
// Remove following two lines in order to perform the submission
// I added the two lines in order to avoid the real submission (Test purposes)
e.preventDefault();
alert('Submitted!')
})
$("#upload").change(function(){
$("#myform").submit();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="example.html" method="post" id="myform" enctype="multipart/form-data">
<input type="file" name="upload" id="upload">
<button id="browse">Upload</button>
</form>
记住删除我包含的"preventDefault"one_answers"alert"行,以便在不重定向到另一个页面的情况下执行代码段。