如果这个问题很愚蠢的话,我真的对ajax很新。我有一个多步骤表单,它有4个部分,我使用$.post()
ajax请求发送它。虽然我的所有其他细节都很顺利,但我无法上传我的文件。这就是我想要做的事情
这里我试图捕捉表格值。
var data_img = new FormData();
var hello = $.each(jQuery('#pan_file')[0].files, function (i, file) {
data_img.append('file-' + i, file);
});
然后我将这些值传递给对象变量。
obj_params.pan_file = hello;
然后使用ajax.post()
$.post('<?php echo base_url(); ?>get-ekyc-form', obj_params, function (msg) {
if (msg == "1") {
swal("Success!", "EKYC Form has been Submitted Successfully", "success");
window.location = '<?php echo base_url(); ?>list-active-requirement';
}
}, "json", "processData:false", "contentType:false");
return true;
这就是我进行文件传输的地方。
if ($_FILES['file-0']['name'] != "") {
$image_data = array();
//config initialise for uploading image
$config['upload_path'] = './media/front/img/quote-docs/';
$config['allowed_types'] = 'xlsx|pdf|doc|docx';
$config['max_size'] = '5000';
$config['max_width'] = '12024';
$config['max_height'] = '7268';
$config['file_name'] = time();
//loading upload library
$this->upload->initialize($config);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file-0')) {
$error = array('error' => $this->upload->display_errors());
} else {
$data = array('upload_data' => $this->upload->data());
$image_data = $this->upload->data();
$file_name = $image_data['file-0'];
}
$file_name = $image_data['file_name'];
} else {
$file_name = '';
}
此外,我正在研究别人的代码,所以我明白我必须犯错误。如果有人可以帮我解决这个问题,我将不胜感激。
答案 0 :(得分:1)
HTML代码
<input id="picture" type="file" name="pic" />
<button id="upload">Upload</button>
$('#upload').on('click', function() {
var file_data = $('#picture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_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(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
在upload.php中
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>