Krajee Bootstrap 文件输入,捕获 AJAX 成功响应
Posted
技术标签:
【中文标题】Krajee Bootstrap 文件输入,捕获 AJAX 成功响应【英文标题】:Krajee Bootstrap File Input, catching AJAX success response 【发布时间】:2015-06-20 00:11:39 【问题描述】:我正在使用 Krajee 引导文件输入插件通过 AJAX 调用执行上传。
这里是 Krajee 插件 AJAX 部分的链接:Krajee plugin AJAX
我使用的 JS 和 php (codeigniter) 代码如下:
JS:
<script>
$("#file-upload").fileinput(
'allowedFileExtensions' : ['csv'],
'maxFileSize': 5120,
'maxFileCount': 1,
'uploadUrl': 'dashboard/uploader',
'elErrorContainer': '#errorBlock',
'uploadAsync': true,
'msgInvalidFileExtension': 'Invalid extension for file "name". Only "extensions" files are supported.',
'uploadExtraData': csrf_token_name: $("input[name=csrf_token_name]").val()
);
</script>
PHP:
public function uploader()
$config['upload_path'] = './csv_uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '5120';
$this->upload->initialize($config);
if (!$this->upload->do_upload("file-upload"))
$data['error'] = 'The following error occured : '.$this->upload->display_errors().'Click on "Remove" and try again!';
echo json_encode($data);
else
echo json_encode("success");
现在我得到了来自 PHP 的响应,无论它是错误还是 JSON 成功,我已经浏览了插件文档,但我仍然找不到如何捕获 AJAX 响应并根据该响应采取行动,因为我们在 jQuery 中使用 ajax 成功函数:
success: function (response)
//Deal with the server side "response" data.
,
我该怎么做?
【问题讨论】:
【参考方案1】:您可以在这里查看演示 live demo
如果你想触发成功事件,记得设置 uploadAsync false
示例代码:
JS
$("#input-id").fileinput(
showRemove:false,
showPreview: false,
uploadUrl: "../xxxx/xxxx/XXXXXX.php", // server upload action
uploadAsync: false,
uploadExtraData: function()
return
bdInteli: xxxx
;
);
// CATCH RESPONSE
$('#input-id').on('filebatchuploaderror', function(event, data, previewId, index)
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
);
$('#input-id').on('filebatchuploadsuccess', function(event, data, previewId, index)
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
alert (extra.bdInteli + " " + response.uploaded);
);
PHP
$nombre = $_FILES["ficheroExcel"]["name"];
$bdInteli = $_POST['bdInteli'];
if (move_uploaded_file($_FILES["ficheroExcel"]["tmp_name"], $nombre) )
$output = array('uploaded' => 'OK' );
else
$output = array('uploaded' => 'ERROR' );
echo json_encode($output);
【讨论】:
@MuhammadYounas 您需要将 uploadAsync 设置为 false。我已经更新了代码【参考方案2】:您可以阅读events section on the plugin documentation page了解插件提供的各种事件。
这取决于您如何在插件中设置 ajax 上传。如文档中所述,该插件提供了两个ajax upload modes - synchronous and asynchronous。如果您将uploadAsync
属性设置为true
,则它是异步的。
AJAX 成功陷阱:
您可以使用filebatchuploadsuccess 事件进行同步 上传 您可以使用fileuploaded 事件进行异步上传对于 AJAX 错误陷阱:
您可以使用filebatchuploaderror 事件进行同步 上传 您可以使用fileuploaderror 事件进行异步上传在您的情况下,您已将 uploadAsync
设置为 true - 因此请使用异步设置/事件。
【讨论】:
这是正确的答案。接受的对我没有用。【参考方案3】:您可以在测试中使用此示例代码。在我的测试中,我的响应数据如下:
response data:
"ver":"1.0",
"ret":true,
"errmsg":null,
"errcode":0,
"data":
"status":"upload success",
"originalFilename":"testFileName.txt",
"fileName":"excelFile",
"fileType":"text/plain",
"fileSize":1733
javascript code:
$('#input-id').on('fileuploaded', function(event, data, previewId, index)
var response = data.response;
if(response.ret )
alert("upload success!"+data.response.data);
else
alert("upload failed!"+response.errmsg)
alert('File uploaded triggered'+form+"response:"+response);
console.info(response.data);
);
【讨论】:
【参考方案4】:refer this answer,我就是这样做的
javascript:
$('#input-id').on('fileuploaded', function(event, data, previewId, index)
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
console.log('File uploaded successfully : ID '+ data.response.d);
);
在 ASHX 文件中添加对上下文的响应:
context.Response.ContentType = "application/json";
string myId = "NewwId 1";
var wrapper = new d = myId ;
context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(wrapper));
【讨论】:
【参考方案5】:<?php echo $form->field($model, 'icon_path')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*','multiple'=>false, 'id' => 'category_icon_image'],
'pluginLoading' => false,
'pluginOptions' => [
'initialPreview' => (!$model->isNewRecord) ? [
'web/filebox/'.$model->icon_path
] : '',
'initialPreviewAsData' => true,
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
'showPreview' => true,
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'showClose' => false,
'previewTemplates' => 'object',
'layoutTemplates' => 'preview',
'uploadUrl' => 'category-item/category-item/ajax-image-upload',
'uploadAsync' => false,
'deleteUrl' => Url::toRoute('category-item/delete-image?id='.$model->category_item_id)
],
'pluginEvents' => [
'filebatchuploadsuccess' => 'function(event, data, previewId, index)
console.log(data.response)
',
'filebatchselected' => "function(event,files)
var input = $('#category_icon_image');
input.fileinput('upload');
$('#categoryitem-icon_path_pre').val(files[0].name);
",
],
])
?>
【讨论】:
以上是关于Krajee Bootstrap 文件输入,捕获 AJAX 成功响应的主要内容,如果未能解决你的问题,请参考以下文章
Bootstrap 5.x/4.x./3.x的增强HTML 5文件输入,具有文件预览、多选和更多功能。