1.引入fileinput相关的css和js(如需要中文显示,则引入对应的中文js包)
2.前端js上传的主要实现方法如下:
$(function () {
loadRole();
initFileInput("pic_path","../SalesImageController/SalesImageController_uploadFile.do");
});
//关闭
function cancle(){
history.back();
}
function initFileInput(ctrlName, uploadUrl) {
var control = $('#' + ctrlName);
control.fileinput({
resizeImage : true,
maxImageWidth : 200,
maxImageHeight : 200,
resizePreference : 'width',
language : 'zh', //设置语言
uploadUrl : uploadUrl,
uploadAsync : true,
allowedFileExtensions : [ 'png', 'jpeg', 'gif', 'jpg' ],//接收的文件后缀
showUpload : true, //是否显示上传按钮
showCaption : true,//是否显示标题
browseClass : "btn btn-primary", //按钮样式
previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
maxFileCount : 10,
msgFilesTooMany : "选择文件超过了最大数量",
maxFileSize : 104857600, //设置最大上传值
layoutTemplates:{
actionDelete: '',//去除上传预览的缩列图中的删除图标
actionUpload: '',//去除上传预览的缩列图中的上传图标
// actionZoom: '',//去除上传预览的缩列图中的预览图标
},
uploadExtraData: function(previewId, index) { //额外参数的关键点
var data = {
messageTitle : $("#messageTitle").val(),
};
return data;
},
}).on('filebatchpreupload', function(event, data) {
if($("#messageTitle").val()==''|| $("#messageTitle").val()==null){
return {
message: "上传失败,请填写标题!",
data:{}
};
}else{
var n = data.files.length, files = n > 1 ? n + '个文件' : '1个文件';
if (!window.confirm("确定上传 " + files + "?")) {
return {
message: "上传取消!!", // upload error message
data:{} // any other data to send that can be referred in `filecustomerror`
};
}else{
if(data.success==false){
return {
message: data.error, // upload error message
data:{} // any other data to send that can be referred in `filecustomerror`
};
}
}
}
});
};
</script>
</head>
<body style="height: 100%;background-color: white;" >
<!-------------------------------搜索框----------------------------------->
<div class="panel panel-default" style="height: 100%;overflow: scroll;">
<div class="panel-body">
<form id="addSalesMessageForm" class="form-inline" enctype='multipart/form-data'>
<div class="form-group" style="width:100%">
<label for="messageTitle"class="col-sm-1 control-label">标题:</label>
<input type="text" class="form-control" ID="messageTitle" name="messageTitle" style="width:81%;" />
</div>
<div class="form-group" style="width: 100%;margin-top:1%;">
<label for="memo"class="col-sm-1 control-label" >上传图片:</label>
<input id="pic_path" name="pic_path" type="file" multiple class="file-loading" style="height:auto">
</div>
<div >
</div>
</form>
<div style="width: 100%;text-align: center;position: absolute;bottom: 1px;">
<a href="javascript:void(0);" class="btn btn-default" onclick="cancle();">关闭</a>
</div>
</div>
</div>
</body>
</html>
3.后台接收保存文件相关数据的实现方法如下:
/***
* 上传文件 用@RequestParam注解来指定表单上的pic_path为MultipartFile
* @author fan
* @date 2018-01-24
*/
@ResponseBody
@RequestMapping(value="SalesImageController_uploadFile")
public Map<String,Object> uploadFile(HttpSession session,@RequestParam("pic_path")MultipartFile myfile,
@RequestParam("messageTitle")String messageTitle) throws IllegalStateException, IOException{
PageData pd = new PageData();
pd = this.getPageData();
IUser user=this.getApUser();
Map<String,Object> map=new HashMap<String,Object>();
//原始名称
String oldFileName = myfile.getOriginalFilename(); //获取上传文件的原名
String file_path = CommonUtil.getConfig("common","SCROLL_DIAGRAM_PATH");//文件基本上传路径
//文件存储的真实路径
File real_path =new File(file_path ) ;
//上传文档
if(myfile!=null && oldFileName!=null && oldFileName.length()>0){
Date date = new Date();
String uuid = UUID.randomUUID().toString().replace("-", "");
//新的文档名称
// String newFileName = user_path+"_"+sdf.format(date)+oldFileName.substring(oldFileName.lastIndexOf("."));
String newFileName = uuid+oldFileName.substring(oldFileName.lastIndexOf("."));
String suffixName = oldFileName.substring(oldFileName.lastIndexOf(".")+1);
if(!real_path.isDirectory()){
real_path.mkdirs();
}
//新文档
File newFile = new File(real_path+"/"+newFileName);
String origPath = real_path+"/"+newFileName;
//将内存中的数据写入磁盘
myfile.transferTo(newFile);
try {
//将文档上传的信息保存到数据库表中(省略)
map.put("result", true);
}catch (Exception e) {
map.put("error", "文档上传失败,请勿重复上传,尽快联系系统管理员!"+e);
// 路径为文件且不为空则进行删除
if (newFile.isFile() && newFile.exists()) {
newFile.delete();
}
map.put("result", false);
e.printStackTrace();
}
}
return map;
}
实现效果图如下:
上传成功