关于php:如何上传文件并将文件表存储到数据库中?

How can I upload a file and store a file table into DB?

我正在使用 dropzone.js 和 Codeigniter 来处理带有文件上传过程的文章发布:

  • 有一个表格可以发表文章
  • 有一个dropzone允许用户上传文件
  • 用户提交文章前,可以上传文件。在这里,我需要一个数据库中的文件表来存储文章 ID 和文件名。

    我的问题是:
    只有在我点击提交表单按钮后,文章才会被存储到数据库中,然后我会得到文章 ID。但是,一旦我将文件拖到 dropzone 中,文件就会被上传。那么如何将"article_id - file_name"对存储到数据库中呢?

    这是我上传文件的代码:

    PHP 上传文件:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public function upload() {
        if (!empty($_FILES)) {
        $tempFile = $_FILES['file']['tmp_name'];
        $fileName = $_FILES['file']['name'];
        $targetPath = getcwd() . '/uploads/';
        $targetFile = $targetPath . $fileName ;
        move_uploaded_file($tempFile, $targetFile);

        // store table in db
        $this->load->database(); // load database
        $this->db->insert('file_table', array('id'=> '', 'article_id' => '', 'file_name' => $fileName, 'created_time'=> date("Y-m-d H:i:s")));
        }
    }

    表单和dropzone的PHP:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <form>
    ...            

       
           Drop files here or click to upload.<br />
           <span class="note">(You might select multiple files here.)</span>
       

    ...
    </form>


    尝试使用 insert_id() 获取最后插入的 ID。


    id 不是自动递增的吗?如果是这样,您不需要传递它,您可以传递 null 或跳过该字段。我在上面看到的 $fileName 变量中有文件名。