【问题标题】:how to upload image from codeigniter to mysql如何将图像从codeigniter上传到mysql
【发布时间】:2019-10-25 10:15:38
【问题描述】:

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

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

这是我的控制器

//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);
});

在更新操作方面需要帮助。感谢您的帮助。

【问题讨论】:

    标签: javascript php mysql codeigniter file-upload


    【解决方案1】:

    你可以通过两种方式来做,

    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; }
    

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

    编码愉快:)

    【讨论】:

    • 我的意思是,如果以前存在于数据库服务器中的数据我想替换它,如果数据不存在,我想通过上传文件来填充它。感谢您的帮助
    【解决方案2】:

    您只需要在数据库中发送照片的名称,然后在您必须添加的模型中

    $this->input->post('databse_column_name')=$variable_name_which_content_file_name
    

    【讨论】:

    • $this->input->post('id_service')=$data_service;无法运行,因为错误代码:消息:无法在写入上下文中使用方法返回值文件名:models/Muser.php
    • 我可以编辑代码:$this->input->post('id_service',$data_service)。这是running no message error, but don't upload data to enter the database to replace现有数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多