首页 > 解决方案 > 如何将图像从codeigniter上传到mysql

问题描述

我是 CodeIgniter 的新手。我不知道如何更新数据库中的表单数据。从数据库插入和显示数据已完成,但无法理解如何更新数据库中的数据。

我已尝试研究此链接,但数据未成功上传。

这是我的控制器

//npwp
$temp1 = explode(".", $_FILES['file_npwp']['name']);
$new_name1 = time().'.'.end($temp1);
$config1['upload_path'] = APPPATH.'/file_npwp/';
$config1['file_name'] = $new_name1;
$config1['overwrite'] = TRUE;
$config1['allowed_types'] = 'jpg|jpeg|png|pdf';
$this->load->library('upload',$config1);
$this->upload->initialize($config1);
if(!$this->upload->do_upload('file_npwp')){
$this->data['error'] = $this->upload->display_errors();

}
$media1 = $this->upload->data('file_npwp');

这是我的模特

$data_service['file_npwp']= $file_lampiran1;
$data_service['file_ktp']= $file_lampiran2;
$data_service['file_po']= $file_lampiran3;
$data_service['file_registrasi']= $file_lampiran4;
$this->db->where('id_service',$this->input->post('id_service'));
$this->db->update('service_sis', $data_service);

这是我的观点

<div class="form-group">
<label for="">File NPWP</label>
<input type="file" name="file_npwp" id="file_npwp" class="form-control">
</div>
<br>
<div id="hasilloadfoto"></div>
<br>
<p>*Pastikan semua form sudah terisi dengan benar</p>
<button id="SaveAccount" class="btn btn-success">Simpan</button>

在我看来,这是我的Javascript

$( function() {
var $signupForm = $( '#myForm' );
$signupForm.validate({errorElement: 'em'});
$signupForm.formToWizard({
submitButton: 'SaveAccount',
nextBtnName:  'Selanjutnya',
prevBtnName:  'Sebelumnya',
nextBtnClass: 'btn btn-primary btn-flat next',
prevBtnClass: 'btn btn-default btn-flat prev',
buttonTag:    'button',
validateBeforeNext: function(form, step) {
var stepIsValid = true;
var validator = form.validate();
$(':input', step).each( function(index) {
var xy = validator.element(this);
stepIsValid = stepIsValid && (typeof xy == 'undefined' || xy);
});
return stepIsValid;
},
progress: function (i, count) {
$('#progress-complete).width(''+(i/count*100)+'%');
}

});
});

function filePreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#hasilloadfoto + img').remove();
$('#hasilloadfoto').after('<img src="'+e.target.result+'" width="450" height="300"/>');
}
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function(){
$("#file_npwp").change(functio () {
filePreview(this);
});

在更新操作中需要帮助。我很感激任何帮助。

标签: javascriptphpmysqlcodeigniterfile-upload

解决方案


你可以通过两种方式

  1. 您可以将图像上传到任何云存储(Aws、Azure 等),然后更新 Db 上的链接
  2. 将图像转换为 base64 并将其更新为数据库中的字符串。

我更愿意执行第一步,我有将示例上传到 Azure 并更新我的数据库的示例

// 这是在 Js 上,使用 ajax,我将发送到控制器函数 uploadImage() {

    var base_url = '<?php echo BASEURL ?>';
    // call ajax to upload image
    //event.preventDefault();
    var file_data = $('#post-image').prop('files')[0];
    var form_data = new FormData();
    form_data.append('uploaded_file', file_data);
    $.ajax({
        url: base_url + "dashboard/uploadImage",
        dataType: 'json',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        type: 'post',
        success: function (aData) {

        },
        error: function (data) {
            alert(data);
        }
    });

}

在控制器上,

公共函数uploadImage(){

// 从请求标头中获取 'api-key' 键

    $data = array();
    if (isset($_FILES ['uploaded_file']['name']) && !empty($_FILES ['uploaded_file']['name'])) {
        $userId = $this->input->post("userId");


        $file_name = $userId . "_" . uniqid() . ".jpg";
        $S3ImgUrl = uploadImageToS3($_FILES ['uploaded_file']['tmp_name'], "app_feed_images", $file_name);


        $data = array(
            'code' => 555,
            'message' => 'Image has been uploaded successfully',
            'url' => $S3ImgUrl
        );
    } else {
        $data['code'] = -111;
        $msg = "failed to upload image to s3";
        $data ['status'] = $this->failed_string;
    }

// var_dump($data); 回声 json_encode($data); }

助手类

函数 uploadImageToS3($tmp, $bucket, $file_name) {

$connectionString = "DefaultEndpointsProtocol=https;AccountName=" . azure_bucket_name . ";AccountKey=" . azure_bucket_key;
$blobClient = MicrosoftAzure\Storage\Blob\BlobRestProxy::createBlobService($connectionString);
$containerName = "app-image/" . $bucket;
$containerUrl = "https://hbimg.blob.core.windows.net/";

$content = fopen($tmp, "r");
$options = new MicrosoftAzure\Storage\Blob\Models\CreateBlockBlobOptions();
$content_type = $_FILES['uploaded_file']['type'];
$options->setContentType($content_type);
$blobClient->createBlockBlob($containerName, $file_name, $content, $options);
return $containerUrl . $containerName . "/" . $file_name; }

在控制器端,我刚刚上传了图像,您可以使用上传的图像链接调用模型类并在您的数据库上更新。

快乐编码:)


推荐阅读