bootstrap-fileinput 基于Boostrap的文件上传插件的用法

本文介绍如何使用FileInput插件实现图片上传功能,包括HTML、JS和PHP代码配置,实现预览、上传和回调处理,适用于网页开发中图片上传场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HTML:

    <script src="../js/jquery-3.2.1.min.js"></script>
    <script src="../js/fileinput.min.js"></script>
    <script src="../js/locales/zh.js"></script>
    <script src="../js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../css/bootstrap.min.css">
    <link rel="stylesheet" href="../css/fileinput.min.css">
    
<input id="txt_file" type="file" name="file" data-show-preview="false" />

JS:

initFileinput();
function initFileinput() {
        var myExtData; //用于存储附加参数
        $("#txt_file").fileinput("destroy");
        $("#txt_file").fileinput({ //创建对象
            language: 'zh',
            showPreview: false,
            theme: 'explorer',
            uploadUrl: 'php/boardMgt.php',
            overwriteInitial: false,
            uploadAsync: true, // 默认为true
            initialPreviewAsData: true,
            allowedFileExtensions: ['jpg', 'jpeg', 'gif', 'png', 'bmp'],
            maxFileSize: 2000,
            language: 'zh',
            showUpload: true,
            showRemove: true,
            cache: false,
            uploadExtraData: function () {
                return myExtData
            }
        }).on("filepreajax", function (event, previewId, index) { //创建附加参数
            myExtData = {
                act: 'uploadIcon'
            };
        }).on("fileuploaded", function (event, data) //回调函数
            {
                $("#showBoardIcon").html("") //清空栏目图标缓存
                $iconPath = data.response.iconPath;
                $("#iconPath").val($iconPath) //记录已上传的图标路径
                $("#showBoardIcon").html("<img src='" + $iconPath.substr(3, $iconPath.length) + "' class='img-fluid'/>")
            });
    }

PHP:

if ($act == "uploadIcon") {
    $extName = pathinfo($_FILES["file"]['name'])['extension']; // 注意 后端仍然是根据文件标签的name属性值来接收数据
    $now=time();

    $iconPath = "../boardIcon/" . $now.  "." . $extName;
    if (file_exists($iconPath)) { 
        unlink($iconPath);  //如果文件已经存在则先删除
    }
    move_uploaded_file($_FILES["file"]["tmp_name"], $iconPath);
    echo (json_encode(array("result" => "ok", "iconPath" => $iconPath)));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值