【问题标题】:Jquery Blue-imp file-upload submitting additional data to a db when uploading multiple filesJquery Blue-imp file-upload 在上传多个文件时向数据库提交附加数据
【发布时间】:2017-10-22 03:19:48
【问题描述】:

我正在使用 Blue-imp 文件上传来上传文件。我创建了一个 cusomUploadHandler 如下,以允许将其他数据持久保存到数据库中,如下所示:(我从一些在线教程中获得了代码 - 但现在找不到)

class CustomUploadHandler extends UploadHandler {

    protected function initialize() {
        $this->db = new mysqli(
            $this->options['db_host'],
            $this->options['db_user'],
            $this->options['db_pass'],
            $this->options['db_name']
        );
        parent::initialize();
        $this->db->close();
    }

    protected function handle_form_data($file, $index) {
        $file->title = @$_REQUEST['title'][$index];
        $file->description = @$_REQUEST['payroll_type'];
    }

    protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
            $index = null, $content_range = null) {
        $file = parent::handle_file_upload(
            $uploaded_file, $name, $size, $type, $error, $index, $content_range
        );
        if (empty($file->error)) {
            $sql = 'INSERT INTO `'.$this->options['db_table']
                .'` (`name`, `size`, `type`, `title`, `description`)'
                .' VALUES (?, ?, ?, ?, ?)';
            $query = $this->db->prepare($sql);
            $query->bind_param(
                'sisss',
                $file->name,
                $file->size,
                $file->type,
                $file->title,
                $file->description
            );
            $query->execute();
            $file->id = $this->db->insert_id;
        }
        return $file;
    }

    protected function set_additional_file_properties($file) {
        parent::set_additional_file_properties($file);
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            $sql = 'SELECT `id`, `type`, `title`, `description` FROM `'
                .$this->options['db_table'].'` WHERE `name`=?';
            $query = $this->db->prepare($sql);
            $query->bind_param('s', $file->name);
            $query->execute();
            $query->bind_result(
                $id,
                $type,
                $title,
                $description
            );
            while ($query->fetch()) {
                $file->id = $id;
                $file->type = $type;
                $file->title = $title;
                $file->description = $description;
            }
        }
    }

    public function delete($print_response = true) {
        $response = parent::delete(false);
        foreach ($response as $name => $deleted) {
            if ($deleted) {
                $sql = 'DELETE FROM `'
                    .$this->options['db_table'].'` WHERE `name`=?';
                $query = $this->db->prepare($sql);
                $query->bind_param('s', $name);
                $query->execute();
            }
        } 
        return $this->generate_response($response, $print_response);
    }

}

我的问题是当有多个文件上传时,CustomUploadHandler 被多次调用并且它没有将描述中的数据提交到数据库。只有最后一条记录被正确保留。这是表单的 HTML:

<form id="fileupload" action="/assets/plugins/jquery-file-upload/server/php/UploadHandler.php" method="POST" enctype="multipart/form-data">
                                    <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
                                    <div class="row fileupload-buttonbar">
                                        <div class="col-lg-7">
                                            <!-- The fileinput-button span is used to style the file input field as button -->
                                            <span class="btn green fileinput-button">
                                                <i class="fa fa-plus"></i>
                                                <span>
                                                     Add files...
                                                </span>
                                                <input type="file" name="files[]" multiple="">
                                            </span>
                                            <!-- The global file processing state -->
                                            <span class="fileupload-process">
                                            </span>
                                        </div>
                                        <!-- The global progress information -->
                                        <div class="col-lg-5 fileupload-progress fade">
                                            <!-- The global progress bar -->
                                            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                                                <div class="progress-bar progress-bar-success" style="width:0%;">
                                                </div>
                                            </div>
                                            <!-- The extended global progress information -->
                                            <div class="progress-extended">
                                                 &nbsp;
                                            </div>
                                        </div>
                                    </div>
                                    <!-- The table listing the files available for upload/download -->
                                    <div class="well">
                                        <table role="presentation" class="table clearfix" >
                                            <tbody class="files">
                                            </tbody>
                                        </table>
                                    </div>
                                </form>

每个文件标题都被正确保留,但是当有多个文件上传时,下拉选择选项会丢失。选择框如下所示:

 <select id="payroll_type" class="form-control" name="payroll_type">
   <option name="payroll_variations" value="">Select File Type</option>
       <option name="payroll_variations" value="Payroll Variations">Payroll Variations</option>
       <option name="starters" value="Starters">Starters</option>
       <option name="leavers" value="Leavers">Leavers</option>
       <option name="ss_changes" value="Master Data Changes">Master Data Changes</option>
 </select>

唯一保存了描述的文件是队列中的最后一个。所有以前的文件都将丢失在各自的选择选项中选择的值。

抱歉,我不知道如何更好地解释这一点。

提前致谢。

【问题讨论】:

    标签: jquery database file-upload blueimp


    【解决方案1】:

    对不起,这个答案来得太晚了。 就我而言,如果文件未上传,则没有理由提供数据;所以我将上传然后收集有关文件的数据分为两步。

    我向显示已上传文件的模板添加了所需的额外输入。 (蓝色小鬼将此标记为“下载模板”)

    单个保存按钮启动 javascript 函数以更新文件数据。 在该函数中,JQRY 访问“下载模板”的每一行,它创建一个 JSON 对象来传输要保存的数据。然后在后面的aspx代码中发布到一个“web方法”。

    详情:

    对蓝色小鬼下载模板稍作修改

    <script id="template-download" type="text/x-jquery-tmpl">
    <tr style="width:96%" class="template-download{{if error}} ui-state-error{{/if}}">
        {{if error}}
    
            <td class="name" style="width:30%" colspan=2>${namefdsa}</td>
            <td class="size">${sizef}</td>
            <td class="error" colspan="2">Error:
                {{if error === 1}}File exceeds upload_max_filesize (php.ini directive)
                {{else error === 2}}File exceeds MAX_FILE_SIZE (HTML form directive)
                {{else error === 3}}File was only partially uploaded
                {{else error === 4}}No File was uploaded
                {{else error === 5}}Missing a temporary folder
                {{else error === 6}}Failed to write file to disk
                {{else error === 7}}File upload stopped by extension
                {{else error === 'maxFileSize'}}File is too big
                {{else error === 'minFileSize'}}File is too small
                {{else error === 'acceptFileTypes'}}Filetype not allowed
                {{else error === 'maxNumberOfFiles'}}Max number of files exceeded
                {{else error === 'uploadedBytes'}}Uploaded bytes exceed file size
                {{else error === 'emptyResult'}}Empty file upload result
                {{else}}${error}
                {{/if}}
            </td>
            <td></td>
        {{else}}
            <td class="name" style="width:15%">
               <a href="${Thumbnail_url}" target="_blank">${reNamed}</a>
            </td>
            <td class="size" style="width:5%">${Length}</td>
            <td style="width:40%"><textarea  style='HEIGHT: 60px;width:90%' rows='2' >(Describe File)</textarea> </td>
            <td class='hdn'> ${DocID}</td>
        {{/if}}
        <td class="delete">
            <button data-type="${delete_type}" data-url="${delete_url}">Delete</button>
        </td>
    </tr>
    

    用于保存每个文件的所有描述文本区域的 javascript 函数的核心

    $("table.files tr:gt(0)").each(function () {
            if ($(this).attr('class') == 'template-download') {
                var DocID = $(this).children("td:eq(3)").text();
                var descptn = $(this).children("td:eq(2)").children('textarea').val();
                var objDD = new Object();
                objDD.ID = DocID;
                objDD.sDescription = descptn;
                objDD.sTyp = 'efs';
    
                // Create a data transfer object (DTO) with the proper structure.
                var DTO = { 'dd': objDD };
    
                $.ajax({
                    type: 'POST',
                    contentType: 'application/json',
                    url: 'Upload.aspx/saveDesc',
                    data: JSON.stringify(DTO),
                    dataType: 'json',
                    success: function (response) {
    
                        if (response.d.status != "success") {
                            msgAlert_js('unable to update document.' + response.d.msg);
                        }
    
                    },
                    error: function (msg) {
                        msgAlert_js('unavoidable unknown error');
                    },
                    processData: false
                });
            }
        });
    

    网络方法背后的代码,一次接受一个文件的数据

    [WebMethod] //async web method to update the decription of each file uploaded
        public static basicResult saveDesc(docDescription dd)//string sTyp, int ID,string docDescription
        {
            basicResult rslt = new basicResult();
    
    
            try
            {
                    // here work with  dd.ID,  dd.sDescription
                    //let save function return good result
                    //  rslt.status = "success";
                    //  rslt.msg = string.Empty;
    
    
            }
            catch (Exception e)
            {
                string stop;
                rslt.status = "error";
                rslt.msg = e.Message;
            }
            return rslt;
        }
    

    结果不超过这个类

    public class basicResult
    {
        public string status { get; set; }
        public string msg { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多