关于文件上传,bootstrap做了很好的封装,通过引用File input插件就能实现很好的上传。下面讲解java语言通过mvc调用bootstrap的实现过程:
先看一下效果图:
可以将文件直接拖拽,或者点击文件选择要上传文件。
有兴趣的话可以看一下官网的demo:http://plugins.krajee.com/file-input-ajax-demo/4
1. html页面引用文件上传js(fileinput.js),css(fileinput.css),并加入标签:
<input id="file-5" class="file" name="myfiles" type="file" multiple data-preview-file-type="any" data-upload-url="${ctxPath}/creditInfo/upload.html">
2. 页面初始化js代码:
$("#file-5").fileinput({
uploadUrl:root+"/creditInfo/upload.html", // 后台使用js方法
uploadAsync: false,
minFileCount: 1,
maxFileCount: 3,
language : 'zh',
msgFilesTooMany:'3',
allowedFileExtensions: ['jpg','png'],
initialPreviewAsData: true // identify if you are sending preview data only and not the markup
}).on('filebatchpreupload', function(event, data) {
if($('.imgClass').length>=3){
var img = $(".kv-preview-thumb");
img[3].remove();
$(".kv-upload-progress").addClass("hide");
return {
message: "最多只能上传三张!"
};
}
});
$('#file-5').on('filebatchuploadsuccess', function(event, data, previewId, index) {
var response = data.response;
$.each(response,function(id,path){//上传完毕,将文件名返回
$("#form").append("<input class='imgClass' name='filePath' type='hidden' value='"+path.pathUrl+"'>");
});
$("#isAlterFile").val("Y");
});
$(".fileinput-remove-button").on("click",function(){ //删除按钮
$('.imgClass').remove();
});
3. controller端代码编写:
@RequestMapping(value="/upload",method=RequestMethod.POST)
@ResponseBody
public List<Map<String,String>> upload(@RequestParam MultipartFile[] myfiles,Long creditId, HttpServletRequest request,HttpServletResponse response,HttpSession session) throws IOException{
logger.info("Entering upload creditId={}",creditId);
//获取当前用户
Long userId = UserUtils.getUserIdBySession(session);
Long companyId = UserUtils.getCompanyIdBySession(session);
String day = DateUtils.date2StringByDay(new Date());//获取当前天
String realPath = request.getSession().getServletContext().getRealPath(File.separator+"upload"+File.separator+day);
File file = new File(realPath);
if (!file.exists()) {//文件夹不存在 创建文件夹
file.mkdirs();
}
response.setContentType("text/plain; charset=UTF-8");
List<Map<String,String>> list = new ArrayList<Map<String,String>>();
String originalFilename = null;
for(MultipartFile myfile : myfiles){
Map<String,String> map = new HashMap<String,String>();
if(myfile.isEmpty()){
logger.info("请选择文件后上传!");
return null;
}else{
originalFilename = myfile.getOriginalFilename();
String extension =FileUtils.getExtension(originalFilename);
if("jpg".equalsIgnoreCase(extension)||"png".equalsIgnoreCase(extension)){
originalFilename=userId+"_"+System.currentTimeMillis()+"."+FileUtils.getExtension(originalFilename);
try {
myfile.transferTo(new File(realPath, originalFilename));
//保存文件路径
//creditFileService.insertFile(File.separator+"upload"+File.separator+day+File.separator+originalFilename, companyId, creditId);
map.put("pathUrl","/upload/"+day+"/"+originalFilename);
list.add(map);
logger.info("load success " + request.getContextPath()+File.separator+"upload"+File.separator+day+File.separator+originalFilename);
logger.info("leaving upload!");
}catch (Exception e) {
logger.info("文件[" + originalFilename + "]上传失败,堆栈轨迹如下");
e.printStackTrace();
logger.info("文件上传失败,请重试!!");
return null;
}
}else{
logger.info("load success 只支持jpg,png格式");
}
}
}
return list;
}
list返回保存的文件名称。
4. 图片修改时要先加载图片,采用如下方式:
function loadFile(url){
//上传start
$("#file-6").fileinput({
uploadUrl:root+"/creditInfo/upload.html", // server upload action
uploadAsync: false,
minFileCount: 1,
maxFileCount: 3,
initialPreview: url,
initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup
initialPreviewFileType: 'image', // image is the default and can be overridden in config below
uploadExtraData: {
img_key: "1000",
img_keywords: "happy, places",
},
language : 'zh',
msgFilesTooMany:'3',
allowedFileExtensions: ['jpg','png'],
initialPreviewAsData: true // identify if you are sending preview data only and not the markup
}).on('filebatchpreupload', function(event, data) {
if($('.imgClass').length>=3){
var img = $(".kv-preview-thumb");
img[3].remove();
$(".kv-upload-progress").addClass("hide");
return {
message: "最多只能上传三张!"
};
}
});}
前端贵在工具的总结!继续加油!