如何使用jQuery的Ajax功能与PHP上传文件? [英] How to upload files using jQuery's ajax function with PHP?
问题描述
下面是我的非工作的尝试:
Here's my nonworking attempt:
<script>
function uploadImageSubmit() {
var imageFile = $('.imageFile').val();
$.ajax({
url: 'ajax.php?request=upload-image&file='+imageFile,
success: function(output) {
alert(output);
}
});
}
</script>
<h2>Upload File</h2>
<form>
<input type="file" class="imageFile" />
<a onClick="uploadImageSubmit()">Upload</a>
</form>
在ajax.php的code:
The code on "ajax.php":
<?php
$action = $_GET['request'];
switch($action) {
case 'upload-image':
$imageFile = $_GET['file'];
$name = $_FILES[$imageFile] ['name'];
$tmpLocation = $_FILES[$imageFile] ['tmp_name'];
$upload = move_uploaded_file($tmpLocation, "files/$name");
echo ($upload) ? $name.' uploaded successfully!' : 'File not uploaded.';
end;
}
?>
我得到没有上传信息文件。我想这是因为,即使字符串可以通过URL传递,文件路径不能出于某种原因。但是,有一次我不知道为什么它不工作。有人能找出什么是错的吗?
I get the message file not uploaded. I think it's because even though strings can be passed via the url, File paths can't for some reason. But then again I have no idea why it's not working. Can someone figure out what's wrong please?
推荐答案
其实,<一个href="https://developer.mozilla.org/en/using_files_from_web_applications#Example.3a.c2.a0Uploading_a_user-selected_file"相对=nofollow> HTML5和新的文件API 通过XmlHtt prequest不支持上传。它精美的作品在Firefox 4和Chrome。
Actually, HTML5 and the new File API does support uploading via XmlHttpRequest. It works beautifully in Firefox 4 and Chrome.
这篇关于如何使用jQuery的Ajax功能与PHP上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!