[英]PHP file-upload using jquery post
让我知道是否有人知道此代码有什么问题。
基本上我想使用jQuery上传文件
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(event) {
$('#form1').submit(function(event) {
event.preventDefault();
$.post('post.php',function(data){
$('#result').html(data);
});
});
});
</script>
</head>
<body>
<form id="form1">
<h3>Please input the XML:</h3>
<input id="file" type="file" name="file" /><br/>
<input id="submit" type="submit" value="Upload File"/>
</form>
<div id="result">call back result will appear here</div>
</body>
</html>
和我的php'post.php'
<?php
echo $file['tmp_name'];
?>
上传的文件名不会返回。 问题是我无法访问上传的文件。
提前致谢! 希夫
基本上我想使用jQuery上传文件
您无法使用AJAX上传文件。 您可以使用使用隐藏iframe的jquery.form插件:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(event) {
$('#form1').ajaxForm(function(data) {
$('#result').html(data);
});
});
</script>
</head>
<body>
<form id="form1" action="post.php" method="post" enctype="multipart/form-data">
<h3>Please input the XML:</h3>
<input id="file" type="file" name="file" /><br/>
<input id="submit" type="submit" value="Upload File"/>
</form>
<div id="result">call back result will appear here</div>
</body>
</html>
还要注意enctype="multipart/form-data"
的enctype="multipart/form-data"
。
另一种可能性是使用HTML5 File API ,它允许您在假定客户端浏览器支持的情况下实现这一点。
不可能使用jQuery $ .post上载文件,但是,使用文件API和XMLHttpRequest,完全可以使用AJAX上载文件,您甚至可以知道已经上载了多少数据……
$('input').change(function()
{
var fileInput = document.querySelector('#file');
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload/');
xhr.upload.onprogress = function(e)
{
/*
* values that indicate the progression
* e.loaded
* e.total
*/
};
xhr.onload = function()
{
alert('upload complete');
};
// upload success
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0))
{
// if your server sends a message on upload sucess,
// get it with xhr.responseText
alert(xhr.responseText);
}
var form = new FormData();
form.append('title', this.files[0].name);
form.append('pict', fileInput.files[0]);
xhr.send(form);
}
不,不,您应该使用jQuery表单插件异步上传文件。 您无法使用jQuery $ .post方法上传文件。 该文件将使用隐藏的iframe上传
另一种方法是通过FileAPI / BlobApi使用HTML5上传
您的upload.php出现错误。
您应该更改此部分。
echo $file['tmp_name'];
至:-
echo $_FILES['file']['tmp_name'];
请尝试使用iframe上传,因为您无法使用$ .post方法发送文件。
您还可以尝试使用jQuery uploadify- http: //www.uploadify.com/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.