这是我的非工作尝试:
<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”上的代码:
<?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传递,文件路径也不能出于某种原因。但是我又不知道为什么它不起作用。有人可以弄清楚出了什么问题吗?
答案 0 :(得分:0)
XmlHttpRequest 不支持上传文件。你需要使用一些隐藏的iframe或flash解决方案。
答案 1 :(得分:0)
您无法使用普通JS / AJAX上传文件。一个众所周知的技巧是将您的文件发布到隐藏的iframe并更新iframe。
答案 2 :(得分:0)
实际上,HTML5 and the new File API支持通过XmlHttpRequest上传。它在Firefox 4和Chrome中运行良好。