从PHP获取Jquery文件上传器的自定义响应

时间:2014-05-12 10:57:56

标签: javascript php jquery file-upload blueimp

我想从PHP服务获取jquery文件上传的自定义响应。

<?php

//database query to insert data

$sql_params['document_name'] = name;
$sql_params['document_location'] =document_location;
$sql_params['document_size'] = document_size;
$sql_params['document_id'] = $document_id;

echo json_encode($sql_params);

?>

Javascript代码:

           this.$('#fileupload').fileupload({
                dataType: 'json',
                add: function(e, data) {
                    var filename = data.files[0].name;

                    var jqXHR = data.submit()
                        .success(function(result, textStatus, jqXHR) {
                            console.log('success');
                            console.log(result);
                            console.log(textStatus);
                        })
                        .error(function(jqXHR, textStatus, errorThrown) {

                        }).complete(function(result, textStatus, jqXHR) {
                            console.log('complete');
                            console.log(result);
                        });
                },
                done: function(e, data) {

                    console.log(data.result);
                },

                progressall: function(e, data) {

                }
            });

            this.$('#fileupload').fileupload('option', {
                url: 'api/app/file',
                maxFileSize: 100000,
                acceptFileTypes: /(\.|\/)(txt|pdf|doc|docx|jpg|gif|xls|xlsx|rtf)$/i
            });

我想把json响应为:

{"document_name":"file (9).txt","document_location":"location","document_size":2720,"document_id":"44"}

但我总是得到:

[{"name":"file (9).txt","size":2720,"type":"text\/plain","url":"location","delete_url":"some URL","delete_type":"DELETE"}]

1 个答案:

答案 0 :(得分:0)

由于Blueimp,您将获得默认响应。您可以使用blueimp中的另一个ajax查询从db获取最新文件;

.....
add: function(e, data) {
    var filename = data.files[0].name;

    var jqXHR = data.submit()
        .success(function(result, textStatus, jqXHR) {
            console.log('success');
            console.log(result);
            console.log(textStatus);
        })
        .error(function(jqXHR, textStatus, errorThrown) {

        }).complete(function(result, textStatus, jqXHR) {
            $.ajax({
                url: "getlatestfile.php",
                method: "POST",
                data: "url=" + result[0].url, // this is unique url of uploaded file
                success: function(response) {
                    //response has doc id
                }

            });
        });
}
....

并在你的php处理程序中;

<强> getlatestfile.php

<?php
......
if (empty($_POST["url"])) {
    die("Url must be specified");
} 

$url = $_POST["url"];

$sql = "SELECT *FROM your_table WHERE url = $url ORDER BY date DESC LIMIT 1";
// get $result
echo $result;