我的视图页面上有多个文件上传小部件,但作为参考,我仅在此处添加了1st,我想做的是,我想使用按钮选择文件,然后通过ajax方法上传文件到目录,然后将文件名重新输入名称为“ passport_copy_upload”字段的输入中。
像这样
此页面上的所有其他文件上传小部件都将起作用,最后,我们将提交表单并让用户感谢您的页面。
问题是:文件未上传到目录,在网络控制台中出现错误:{“错误”:“您没有选择要上传的文件。”}
我的观点部分
<form id="fimilyVisaForm" action="https://www.mydomainurl.com/visa/add-other-details/<?php echo $appid;?>" method="post" enctype="multipart/form-data" onsubmit="return(validate());">
<h4 class="row marginBottom">Upload Documents</h4>
<div class="form-control">
<div class="col-sm-4 label">Colored Scanned copy of the Passport</div>
<div class="col-sm-3">
<input type="text" class="form-control-input" placeholder="Colored Scanned copy of the Passport" name="passport_copy_upload" id="passport_copy_upload" onclick="removeError(this.id);" value="">
</div>
<div class="col-sm-3">
<input type="button" class="submit-btn read-more" value="Attach" id="passport">
<input type="file" name="passportimg" id="passportimg" style="display:none">
<a id="viewct" class="submit-btn read-more" href="#">View</a>
<div class="labelInfo">Colored Scanned copy of the Passport</div>
</div>
</div>
</form>
<script>
document.getElementById('passport').onclick = function() {
document.getElementById('passportimg').click();
};
</script>
Javascript Ajax代码
<script>
$("#passportimg").change(function() {
var file_data = $("#passportimg").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
$.ajax({
url:'<?= base_url();?>index/do_upload',
dataType: 'json',
cache: false,
async: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success:function(data)
{
console.log(data);
}
});
});
</script>
这是我的控制人
public function do_upload() {
header('Content-Type: application/json');
$config['upload_path'] = '<?= base_url();?>uploads/applicant/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 2048;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('passportimg')) {
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}else {
$data = $this->upload->data();
$success = ['success'=>$data['file_name']];
echo json_encode($success);
}
}
答案 0 :(得分:2)
请替换:
var file_data = $("#passportimg").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
收件人:
var form = $("#fimilyVisaForm")[0];
var form_data = new FormData(form);