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)));
}