gpt4 book ai didi

javascript - 无法使用ajax上传文件

转载 作者:行者123 更新时间:2023-11-29 16:38:35 24 4
gpt4 key购买 nike

我正在尝试使用ajax上传表单数据,但问题是我无法上传图像/文件。

表单代码

<form class="form-inline" id="form_add"  enctype="multipart/form-data"> 
<input type="file" id="file-input" name="file-input" accept="image/*" >

<input type="text" class="form-control name" id="fname" placeholder="First Name" >
<select class="location" id="location" >
<option value="">Location</option>
<?php foreach($location as $loc): ?>
<option value="<?php echo $loc->city.', '.$loc->state;?>" ><?php echo $loc->city.', '.$loc->state;?></option>
<?php endforeach; ?>
</select>
<button type="submit" class="save_btn" id="submit" > <img src="save.png" class="Save"> </button>
</form>

脚本代码

<script>
$("#submit").click(function()
{
event.preventDefault();
var filename = $('input[type=file]').val();
var fname = $("#fname").val();
var location = $("#location").val();
if(filename != "" || fname != "" || location != "")
{
$.ajax({
type: "POST",
url: "Data/add_data",
data: {
filename : filename,
fname:fname,
location:location
},
cache: false,
success: function(result){
console.log(result);
}});
}
});
</script>

后端代码

$ImageFile = $this->input->post('filename');
$config['upload_path'] = './assets/client_img/.';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);

if (!$this->upload->do_upload('ImageFile'))
{
$error1 = array('error' => $this->upload->display_errors());
print_r($error1);
}
else
{
$data1 = $this->upload->data();
echo $data1['file_name'];
}

在后端代码中,我获取 $ImageFile 的值为 C:\fakepath\pic.jpg 但该文件未上传,并且错误提示

You did not select a file to upload

谁能告诉我如何上传文件

最佳答案

$("#submit").click(function ()
{
event.preventDefault();
var filename = $('input[type=file]').val();
var fname = $("#fname").val();
var location = $("#location").val();


if (filename != "" || fname != "" || location != "")
{
var formData = new FormData();
formData.append('filename', $('input[type=file]')[0].files[0]);
formData.append('fname', fname);
formData.append('location', location);
$.ajax({
type: "POST",
url: "Data/add_data",
data: formData,
contentType: false,
processData: false,
cache: false,
success: function (result) {
console.log(result);
}});
}
});

关于javascript - 无法使用ajax上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48822445/

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