这可能是重新发布,因为我可能没有在stackoverflow中搜索得足够深,尽管我发现的一些帖子对我没有帮助。所以我想做一件简单的事 - 用ajax上传图片。我有这个HTML:
<form class="form-inline" id="navigationLinkCreationForm" >
<input type="text" class="form-control" placeholder="Nuorodos pavadinimas" id="linkName" />
<label class="btn btn-default btn-file">
Įkelti ikoną(1:1)<input id="selectNavigationIcon" name="navigationIcon" type="file" style="display: none;">
</label>
<input type="submit" class="btn btn-success" id="createLinkButton" value="Sukurti nuorodą" />
</form>
然后我有了这个ajax:
$('#createLinkButton').on('click', uploadFiles);
function uploadFiles(event)
{
event.preventDefault();
var formData = new FormData($('#navigationLinkCreationForm'));
$.ajax({
type: 'POST',
url: '../php_includes/uploadNavigationIcon.php',
data:formData,
success: function (data)
{
console.log(data);
},
processData: false,
contentType: false,
cache: false
});
}
最后我有一个简单的uploadNavigationIcon.php文件,如果已提交文件,则只输出“S”
<?php
if(isset($_GET['files']))
{
echo "S";
}
运行之后,我只是获得空输出,这意味着文件没有提交。
答案 0 :(得分:1)
试试这个,它是经过测试和运行的代码:
$(document).ready(function(){
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
});
upload.php的
<?php
if ( $_FILES['file']['error'] > 0 ){ // file data can't be fetched by using $_GET
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>