无论我做什么,我似乎无法通过AJAX将文件上传到CodeIgniter方法。它总是抛出,永远不会看到上传的文件。
HTML
<div>
<h1>Upload Your Translation</h1>
</div>
<form method="POST" class="myForm" enctype="multipart/form-data">
<!-- add your span and pther stuff here-->
<input type="file" id="foto1" name="userfile" />
<input type="button" value="submit" onclick="submitFile();" />
</form>
<script>
function submitFile(){
var formUrl = "/system_administration/AJAX_upload_translation";
var formData = new FormData($('.myForm')[0]);
$.ajax({
url: formUrl,
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data, textSatus, jqXHR){
//now get here response returned by PHP in JSON fomat you can parse it using JSON.parse(data)
},
error: function(jqXHR, textStatus, errorThrown){
//handle here error returned
}
});
}
</script>
PAYLOAD
Request Method:POST
Status Code:200 OK
------WebKitFormBoundaryvkN2BT8ZDxXmKj7Y
Content-Disposition: form-data; name="userfile"; filename="clippy-windows-8-10.jpg"
Content-Type: image/jpeg
function AJAX_upload_translation()
{
if (!isset($_FILES['userfile']['error']) || is_array($_FILES['userfile']['error']))
{
throw new RuntimeException('Invalid parameters.');
}
}
答案 0 :(得分:1)
设置表单操作路径并将其用于ajax(最好不要使用onclick函数)
$(document).on("submit", ".myForm", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),//set form action url at your form
type: $(this).attr("method"),//set form method at your form
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
答案 1 :(得分:1)
试试这段代码..
$('#upload').on('click', function() {
var file_data = $('#foto1').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'your_upload_php_file', // 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(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});