将上传的文件路径存储到数据库mysql并下载

将上传的文件路径存储到数据库mysql并下载

问题描述:

I am using codeigniter and now I want to upload the file path to the table. This code below only storing the folder path, like '
http://localhost/kirimundangan.com/kirim_undangan/' not the actual file name. I expected like 'http://localhost/kirimundangan.com/kirim_undangan/somefile.xlsx'.

Function upload when user upload file via dropzone:

function upload() 
    {
        $this->load->library('session');
        
        if (!empty($_FILES)) 
        {
            $filename = $_FILES["file"]["name"];
            $file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
            $file_ext = substr($filename, strripos($filename, '.')); // get file name

            $tempFile = $_FILES['file']['tmp_name'];
            $data = uniqid(). $file_ext;
            $targetPath = getcwd() . '/kirim_undangan/';
            $targetFile = $targetPath . $data ;

            move_uploaded_file($tempFile, $targetFile);
            $_SESSION["xls"] = $data;
            print_r($_SESSION['xls']);
        }

Function undangan when user submit input text along with the uploaded file :

function undangan()
    {$email          =   $this->input->post('email');
            $from_nama      =   $this->input->post('from_nama');
            $from_phone     =   $this->input->post('from_phone');
 $filename = $_FILES["file"]["name"];
            $file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
            $file_ext = substr($filename, strripos($filename, '.')); // get file name

            $tempFile = $_FILES['file']['tmp_name'];
            $data_file = uniqid(). $file_ext;
            $targetPath = getcwd() . '/kirim_undangan/';
            $targetFile = $targetPath . $data ;

            $data_user = array(

                'email'                         => $email,
                'name'                          => $from_nama,
                'phone'                         => $from_phone,
                'status'                        => '0',
                'filename_user'                 => site_url('/kirim_undangan/.uniqid()'),

                );
            $this->load->model('excel');
            $this->excel->tambahuser($data_user); 

The model :

 function tambahuser($data_user)
        {
            $this->db->insert('request', $data_user);
            $this->db->insert_id();
            
            foreach ($data_user as $key)     
            {  
                $data = array(
                    'from_name'          =>   $this->input->post('from_nama'),
                    'from_phone'         =>   $this->input->post('from_phone')
                );
            }
             
        }

And the view :

<div class="modal-body">

                    <div id="form_pesan">
                
                        <div action="<?php echo site_url('/kirim/upload'); ?>" class="dropzone" id="dropzone_form">
                            <div class="dz-message" data-dz-message><span><h4>Klik atau drop file Disini
</h4></span></div>
                        </div>
                        <div class="row" id="form_user" style="display: none;">
                            
                            <h4 id="form">Data Personal</h4>

                            <div class="col-sm-4">
                                <input type="email" class="form-control input-lg" id="email"  name="email"  placeholder="Email" required>
                            </div>

                            <div class="col-sm-4">
                                <input type="text" class="form-control input-lg"  id="from_nama" name="from_nama" placeholder="Nama" required>
                            </div>

                            <div class="col-sm-4">
                                <input type="number" class="form-control input-lg"  id="from_phone"  name="from_phone" placeholder="Phone" required>
                            </div>
                            <div>
                               <input type="hidden" name="id" id="id" />
                            </div>
                            <br>
                            <div class="row" align="center">
                                <button id="pesan" type="button" class="btn btn-download btn-md" onclick=pesan()>
                                <span class="glyphicon glyphicon-send" aria-hidden="true" ></span>Pesan
                                </button>
                            </div>

                         </div>

If the path is store into table, I will use it to download the file. Btw, is storing a file path into database is better practice than storing the actual file? (I need to store a xls or doc file)

my form :

when dropzone success upload, it hide

showing this

javascript :

Dropzone.autoDiscover = false;
var myDropzone = new Dropzone('#dropzone_form',{
    acceptedFiles: ".xlsx, .xls, .docs, .doc, .pdf" ,
    "maxFiles":1 ,
    init: function () {
        var thisDropzone = this;

        this.on("success", function(files, response) {
            $('#alert_drpzone').show();
            $('#form_user').show();
            $('#dropzone_form').hide();
            $('#myModalLabel').hide();
        });

        this.on("error", function(files,response) {
            $('#alert2').show();
        })
    }
});


function pesan()
    { 
        email = $("#email").val(); 
        from_nama = $("#from_nama").val(); 
        from_phone = $("#from_phone").val(); 

        $.ajax
        ({
            url : "<?php echo site_url('kirim/undangan')?>/",
            type: "POST",
            dataType: "text",
            data:{from_nama: from_nama, email: email, from_phone: from_phone},
            success: function(data)
            {       
               $('#alert_sukses').show();
               $('#form_pesan').hide();
               $('#myModalLabel').hide();
               $('#email'+data).html(data.email);
               $('#from_nama'+data).html(data.from_nama);
               $('#from_phone'+data).html(data.from_phone);
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert('Error upload data');
            }

        });
    }

</div>

You didn't call the upload() in undangan(). In upload() return $targetFile so that it will give you the uploaded file name then add that name into $data_user.

function upload() 
{   
    if (!empty($_FILES)) 
    {
        $filename = $_FILES["file"]["name"];
        $file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
        $file_ext = substr($filename, strripos($filename, '.')); // get file name

        $tempFile = $_FILES['file']['tmp_name'];
        $data = uniqid(). $file_ext;
        $targetPath = getcwd() . '/kirim_undangan/';
        $targetFile = $targetPath . $data ;

        move_uploaded_file($tempFile, $targetFile);
        return $targetFile; //return uploaded file name with directory
    }

change controller like

function undangan()
{
        $email          =   $this->input->post('email');
        $from_nama      =   $this->input->post('from_nama');
        $from_phone     =   $this->input->post('from_phone');
        $uploadedFileName = $this->upload();

        $data_user = array(
            'email'                         => $email,
            'name'                          => $from_nama,
            'phone'                         => $from_phone,
            'status'                        => '0',
            'filename_user'                 => $uploadedFileName,

            );
        $this->load->model('excel');
        $this->excel->tambahuser($data_user); 
}

Hope this will solve your problem. If you need any help. Im happy to guide you