1.文件上传
前端代码:
1 html代码:<%--layui自带的原始的文件上传控件--%> 2 <input type="file" name="file" id="test20"> 3 js代码:<%--accept为上传文件指定格式,file为所有文件类型,url为上传到后台的路径 --%> 4 layui.use('upload', function(){ 5 var $ = layui.jquery 6 ,upload = layui.upload; 7 //绑定原始文件域 8 upload.render({ 9 elem: '#test20' 10 ,accept: 'file' 11 ,url: '${ctx}/fpPlaceFile/uploadFile/${placeId}' 12 }); 13 });
后台代码:
//controller层使用MultipartFile file参数接受前台传过来的文件信息 public int uploadFile(MultipartFile mFile, HttpServletRequest request,String strPath, String relativedId,String strRelativedType,String strDesc) throws Exception { //获取user信息 Subject subject = SecurityUtils.getSubject(); MyShiroRealm.ShiroUser shiroUser = (MyShiroRealm.ShiroUser) subject.getPrincipal(); String userName = shiroUser.getUser().getStrAccount(); User user = shiroUser.getUser(); //指定文件存放相对路径 String contentUploadPath = "/static/uploadFiles/" + strPath; //绝对路径 String appPath = request.getSession().getServletContext().getRealPath(contentUploadPath); String strFileName = ""; String strFilePath = ""; //判断文件是否为空 if (!mFile.isEmpty()) { //补充绝对路径 File uploadFileDirct = new File(appPath, userName + "/" + relativedId); //路径为空,则创建该路径 if (!uploadFileDirct.exists()) { uploadFileDirct.mkdirs(); } //获取文件名 strFileName = mFile.getOriginalFilename(); //获取文件格式 String suffixName = strFileName.substring(strFileName.lastIndexOf(".") + 1); String fileName = strDesc+strFileName; File uploadFile = new File(uploadFileDirct, fileName); //补充相对路径 strFilePath = contentUploadPath + "/" + userName + "/" + relativedId + "/" + fileName; //上传文件 mFile.transferTo(uploadFile); NjAttach njAttach = new NjAttach(); njAttach.setId(fid); njAttach.setStrName(strFileName); BigDecimal b = new BigDecimal((double) mFile.getSize() / 1024); double fileSize = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); njAttach.setDoubleSize(fileSize); njAttach.setStrDocType(suffixName); njAttach.setRelativedId(relativedId); njAttach.setStrRelativedType(strRelativedType); njAttach.setStrDesc(strDesc); njAttach.setStrPath(strFilePath); njAttach.setCreateUser(user); njAttach.setCreateDateTime(DateTools.getFullNowDateTime()); return this.addAttach(njAttach); }else { throw new ServiceException("上传失败,文件为空或未选择文件!"); } }
删除文件
前台代码:
1 <a class="delete btn-small" target="dialog" 2 dialogId="upadteFcHydrantDialog22" href="${ctx}/fpPlaceFile/delete/${fpPlaceFile.id}">删除</a>
后台代码:
1 //先获取文件的绝对路径和在服务器保存的文件名 2 String url = fpPlaceFileService.findOneById(id).getFileUrl(); 3 String name = fpPlaceFileService.findOneById(id).getUid(); 4 String affiPath = url +"/" + name; 5 File pdfFile = new File(request.getSession().getServletContext().getRealPath(affiPath)); 6 pdfFile.delete();
文件下载
前台代码,无后台代码:
1 <%--直接获取文件的路径和文件名,通过url下载,如果文件是图片,则直接打开--%> 2 <a class="download btn-small" 3 href="${ctx}${fpPlaceFile.fileUrl}/${fpPlaceFile.uid}">下载</a>