一、导入zyupload所需js、css、jquery等配置文件
二、关键代码
1、html 前端
首先在<script></script>内初始化插件:
$("#zyupload").zyUpload({ width: "650px", // 宽度 height: "auto", // 宽度 itemWidth: "140px", // 文件项的宽度 itemHeight: "115px", // 文件项的高度 url: "../uploadimg/upload.do?ajbh=${ajbh}", // 上传文件的路径 fileType: ["jpg", "png", "js"],// 上传文件的类型 fileSize: 51200000, // 上传文件的大小 multiple: true, // 是否可以多个文件上传 dragDrop: false, // 是否可以拖动上传文件 tailor: false, // 是否可以裁剪图片 del: true, // 是否可以删除文件 finishDel: false, // 是否在上传文件完成后删除预览 /* 外部获得的回调接口 */ onSelect: function (selectFiles, allFiles) { // 选择文件的回调方法 selectFile:当前选中的文件 allFiles:还没上传的全部文件 console.info("当前选择了以下文件:"); console.info(selectFiles); }, onDelete: function (file, files) { // 删除一个文件的回调方法 file:当前删除的文件 files:删除之后的文件 console.info("当前删除了此文件:"); console.info(file.name); }, onSuccess: function (file, response) { // 文件上传成功的回调方法 console.info("此文件上传成功:"); console.info(file.name); console.info("此文件上传到服务器地址:" + response); var last = response.substr(); var path = $("input[name='xsImgs']").val(); if (path != null && path != "") { //两次上传情况下前台完成异步拼接 path = path + "||" + last; } else { path = last; } $("input[name='xsImgs']").val(path); $("#uploadInf").append("<p>上传成功</p>"); }, onFailure: function (file, response) { // 文件上传失败的回调方法 console.info("此文件上传失败:"); console.info(file.name); }, onComplete: function (response) { // 上传完成的回调方法 console.info("文件上传完成"); console.info(response); } });在页面某处:
<input type="hidden" name="xsImgs" value=""/>
然后在需要应用的位置插入
<div id="zyupload" class="zyupload"></div>
即可
2、zyupload/skins/js
搜索:
formdata.append(
"file"
, file);
前面引号内对应后台接收元素名称,java下是
@RequestParam("file") MultipartFile[] file
后面对应前端初始化时内部使用的名称,一般是file不需更改
3、后台关键代码【java,springmvc
】
Controller层
@ResponseBody @RequiresPermissions("core::upload") @RequestMapping(value = "/upload.do",method= RequestMethod.POST,produces = "text/html;charset=UTF-8") public String uploadFile(@RequestParam("file") MultipartFile[] file,HttpServletRequest request) throws IOException { String firstPath = "";//存入数据库的路径前缀 String prePath = request.getSession().getServletContext().getRealPath(firstPath);//组成文件存放路径前缀 String finalPath=service.uploadFile(firstPath,prePath,file);//上传文件并得到存入数据库的完整路径 return finalPath; }ServiceImpl层
public String uploadFile(String firstPath, String prePath, MultipartFile[] file) throws IOException { String finalPath = ""; for (int i = 0; i < file.length; i++) {//循环存入文件并组合路径 MultipartFile thisfile = file[i]; String fileName = thisfile.getOriginalFilename();//得到文件名称 if (fileName != "" && !thisfile.isEmpty()) { if (i + 1 < file.length) finalPath = finalPath + firstPath + fileName + "||";//判断是否要加分隔符,如果没有文件则返回null else if (!thisfile.isEmpty()) finalPath = finalPath + firstPath + fileName; String accessPath = prePath + "/" + fileName; File dest = new File(accessPath); if (!dest.getParentFile().exists()) {// 检测是否存在目录 dest.getParentFile().mkdirs(); } thisfile.transferTo(dest);//写入文件 } else return finalPath; } return finalPath; }