在CodeIgniter中使用Ajax上传图片的步骤如下:
do_upload()
方法来处理文件上传。在上传成功后,可以获取上传后的文件信息,如文件名、文件路径等。$.ajax()
方法来发送POST请求,并将文件数据作为FormData对象的一部分发送。在请求成功后,可以根据返回的数据进行相应的处理,如显示上传成功的消息或者显示上传后的图片。下面是一个示例代码:
<form id="uploadForm" action="#" method="post" enctype="multipart/form-data">
<input type="file" name="userfile" id="userfile">
<input type="submit" value="Upload" id="uploadBtn">
</form>
<div id="message"></div>
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index() {
$this->load->view('upload_form');
}
public function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
$error = $this->upload->display_errors();
echo json_encode(array('status' => 'error', 'message' => $error));
} else {
$data = $this->upload->data();
echo json_encode(array('status' => 'success', 'message' => 'File uploaded successfully.', 'file' => $data['file_name']));
}
}
}
?>
$(document).ready(function() {
$('#uploadForm').submit(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'upload/do_upload',
type: 'POST',
data: formData,
dataType: 'json',
processData: false,
contentType: false,
success: function(response) {
if (response.status === 'success') {
$('#message').html(response.message);
// 显示上传后的图片
$('#uploadedImage').attr('src', 'uploads/' + response.file);
} else {
$('#message').html(response.message);
}
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
});
请注意,上述示例中的代码仅供参考,实际使用时可能需要根据具体需求进行适当的修改和调整。
领取专属 10元无门槛券
手把手带您无忧上云