gpt4 book ai didi

javascript - 通过 ajax $.post 上传文件不起作用

转载 作者:行者123 更新时间:2023-12-03 04:13:54 24 4
gpt4 key购买 nike

我对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 = '';
}

此外,我正在处理别人的代码,所以我确实知道我一定犯了很多错误。如果有人能帮助我解决这个问题,我将不胜感激。

最佳答案

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']);
}

?>

关于javascript - 通过 ajax $.post 上传文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44223859/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com