下面写的这个是根据实际项目中的内容写的,你们看的时候稍微注意下哈。
fileinput插件下载地址:https://github.com/kartik-v/bootstrap-fileinput/releases
<script type="application/javascript" src="/lib/js/jquery-3.1.1.js"></script>
<script type="application/javascript" src="/lib/js/fileinput.js"></script>
<script type="text/javascript"
src="/lib/js/zh.js"></script>
<input type="button" class="btn btn-primary" id="addBtn" value="添加"/>
<!--添加操作模态框-->
<div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel1">新闻添加</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" action="" method="post">
<div class="item">
<h3>新闻添加</h3>
</div>
<div class="item">
新闻标题:
<input type="text" class="form-control" name="title" id="title-1"
placeholder="请输入标题"/><span
class="state1"></span></div>
<div class="item">
新闻内容:
<textarea class="form-control" name="content" id="content-1" rows="3"></textarea>
<span
class="state1"></span></div>
<div class="form-group">
<label class="col-sm-2 control-label">新闻图片</label>
<div class="col-sm-10">
<input type="file" name="imagepath" data-ref="url2"
class="col-sm-10 myfile" value=""/> <input type="hidden"
name="url2" id="imagepath-1" value="">
</div>
</div>
<div class="item">
<button type="button" id="addBtn1" class="btn btn-primary" data-dismiss="modal"><span
class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>保存
</button>
<button type="button" class="btn btn-default" data-dismiss="modal"><span
class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭
</button>
</div>
</form>
</div>
</div>
</div>
</div>
//上传图片操作
$(".myfile").fileinput({
uploadUrl: "/noticeManager/notice/uploadFile", //接受请求地址
uploadAsync: true, //默认异步上传
showUpload: false, //是否显示上传按钮,跟随文本框的那个
showRemove: false, //显示移除按钮,跟随文本框的那个
showCaption: true,//是否显示标题,就是那个文本框
showPreview: true, //是否显示预览,不写默认为true
dropZoneEnabled: false,//是否显示拖拽区域,默认不写为true,但是会占用很大区域
//minImageWidth: 50, //图片的最小宽度
//minImageHeight: 50,//图片的最小高度
//maxImageWidth: 1000,//图片的最大宽度
//maxImageHeight: 1000,//图片的最大高度
//maxFileSize: 0,//单位为kb,如果为0表示不限制文件大小
//minFileCount: 0,
maxFileCount: 1, //表示允许同时上传的最大文件个数
enctype: 'multipart/form-data',
validateInitialCount: true,
previewFileIcon: "",
msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
allowedFileTypes: ['image'],//配置允许文件上传的类型
allowedPreviewTypes: ['image'],//配置所有的被预览文件类型
allowedPreviewMimeTypes: ['jpg', 'png', 'gif'],//控制被预览的所有mime类型
language: 'zh'
})
//异步上传返回结果处理
$('.myfile').on('fileerror', function (event, data, msg) {
console.log("fileerror");
console.log(data);
});
//异步上传返回结果处理
$(".myfile").on("fileuploaded", function (event, data, previewId, index) {
console.log("fileuploaded");
var ref = $(this).attr("data-ref");
var aa = $("input[name='" + ref + "']").val(data.response.url);
var jsonData = JSON.stringify(aa);// 转成JSON格式
var result = $.parseJSON(jsonData);// 转成JSON对象
});
//上传前
$('.myfile').on('filepreupload', function (event, data, previewId, index) {
var form = data.form, mynewpic = data.mynewpic, extra = data.extra,
response = data.response, reader = data.reader;
console.log("文件正在上传。。。。");
});
@RequestMapping("/uploadFile")
@ResponseBody
public Map<String, Object> uploadFile(MultipartFile imagepath) throws IllegalStateException, IOException {
String mynewpic = null;
// 原始图片名称
String oldFileName = imagepath.getOriginalFilename(); // 获取上传文件的原名
// 存储路径
if (imagepath != null && oldFileName != null && oldFileName.length() > 0) {
//我这写的是绝对路径请注意,springboot 用内置tomcat 展示图片会有问题 稍后在看
String saveFilePath = "D:\\666";
File files = new File(saveFilePath);
if (!files.exists()) {
files.mkdirs();
}
// 新的图片名称
String newFileName = UUID.randomUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));
// 新图片
File newFile = new File(saveFilePath + "\\" + newFileName);
// 将内存中的数据写入磁盘
imagepath.transferTo(newFile);
// 将路径名存入全局变量mynewpic
mynewpic = newFileName;
// 将新图片名称返回到前端
Map<String, Object> map = new HashMap<String, Object>();
map.put("success", "成功啦");
map.put("url", mynewpic);
return map;
} else {
Map<String, Object> map = new HashMap<String, Object>();
map.put("error", "图片不合法");
return map;
}
}
//执行添加操作
$('#addBtn1').click(function () {
// window.parent.document.close();
var title = $("#title-1").val();
var content = $("#content-1").val();
var imagepath = $("#imagepath-1").val();
$.ajax({
type: "post",
datatype: "json",
url: "/noticeManager/notice/save",
data: {
"title": title, "content": content, "imagepath": imagepath},
async: true,
success: function (result) {
//console.log(result);
if (result.flag == 'success') {
$("#noticeTable").bootstrapTable('refresh');
toastr.success("添加成功!");
} else {
toastr.error("添加失败!");
}
}
});
});