package com.cnpc.framework.base.controller; import com.cnpc.framework.base.entity.SysFile; import com.cnpc.framework.base.entity.User; import com.cnpc.framework.base.pojo.AvatarResult; import com.cnpc.framework.base.pojo.FileResult; import com.cnpc.framework.base.pojo.MarkDownResult; import com.cnpc.framework.base.pojo.Result; import com.cnpc.framework.base.service.UploaderService; import com.cnpc.framework.util.SecurityUtil; import com.cnpc.framework.utils.DateUtil; import com.cnpc.framework.utils.FileUtil; import com.cnpc.framework.utils.PropertiesUtil; import com.cnpc.framework.utils.StrUtil; import org.apache.commons.fileupload.util.Streams; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.*; import java.util.*; @Controller @RequestMapping("/file") public class UploaderController { private static Logger logger= LoggerFactory.getLogger(UploaderController.class); //previewFileIconSettings public static Map fileIconMap=new HashMap(); @Resource private UploaderService uploaderService; static { fileIconMap.put("doc" ,"<i></i>"); fileIconMap.put("docx","<i></i>"); fileIconMap.put("xls" ,"<i></i>"); fileIconMap.put("xlsx","<i></i>"); fileIconMap.put("ppt" ,"<i></i>"); fileIconMap.put("pptx","<i></i>"); fileIconMap.put("jpg" ,"<i></i>"); fileIconMap.put("pdf" ,"<i></i>"); fileIconMap.put("zip" ,"<i></i>"); fileIconMap.put("rar" ,"<i></i>"); fileIconMap.put("default" ,"<i></i>"); } //从setting.properties文件中注入文件相对目录(相对目录为显示文件) //@Value("${uploaderPath}") 只有配置@Config才能注入 private static final String uploaderPath=PropertiesUtil.getValue("uploaderPath"); /** * 跳转到通用文件上传窗口 * @return */ @RequestMapping(value="/uploader",method = RequestMethod.GET) public String uploader(String config,HttpServletRequest request){ request.setAttribute("config",config); return "base/file/file_uploader"; } /** * 通用文件上传接口,存储到固定地址,以后存储到文件服务器地址 */ @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) @ResponseBody public SysFile uploadFile(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) { //TODO dosomething return new SysFile(); } /** * 多文件上传,用于uploadAsync=false(同步多文件上传使用) * @param files * @param request * @param response * @return */ @RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST) @ResponseBody public FileResult uploadMultipleFile(@RequestParam(value = "file", required = false) MultipartFile[] files, HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("the num of file:"+files.length); FileResult msg = new FileResult(); ArrayList<Integer> arr = new ArrayList<>(); //缓存当前的文件 List<SysFile> fileList=new ArrayList<>(); String dirPath = request.getRealPath("https://www.jb51.net/"); for (int i = 0; i < files.length; i++) { MultipartFile file = files[i]; if (!file.isEmpty()) { InputStream in = null; OutputStream out = null; try { File dir = new File(dirPath+uploaderPath); if (!dir.exists()) dir.mkdirs(); //这样也可以上传同名文件了 String filePrefixFormat="yyyyMMddHHmmssS"; System.out.println(DateUtil.format(new Date(),filePrefixFormat)); String savedName=DateUtil.format(new Date(),filePrefixFormat)+"_"+file.getOriginalFilename(); String filePath=dir.getAbsolutePath() + File.separator + savedName; File serverFile = new File(filePath); //将文件写入到服务器 //FileUtil.copyInputStreamToFile(file.getInputStream(),serverFile); file.transferTo(serverFile); SysFile sysFile=new SysFile(); sysFile.setFileName(file.getOriginalFilename()); sysFile.setSavedName(savedName); sysFile.setCreateDateTime(new Date()); sysFile.setUpdateDateTime(new Date()); sysFile.setCreateUserId(SecurityUtil.getUserId()); sysFile.setDeleted(0); sysFile.setFileSize(file.getSize()); sysFile.setFilePath(uploaderPath+File.separator+savedName); uploaderService.save(sysFile); fileList.add(sysFile); /*preview.add("<div class=\"file-preview-other\">\n" + "<span class=\"file-other-icon\"><i class=\"fa fa-file-o text-default\"></i></span>\n" + "</div>");*/ logger.info("Server File Location=" + serverFile.getAbsolutePath()); } catch (Exception e) { logger.error( file.getOriginalFilename()+"上传发生异常,异常原因:"+e.getMessage()); arr.add(i); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } } else { arr.add(i); } } if(arr.size() > 0) { msg.setError("文件上传失败!"); msg.setErrorkeys(arr); } FileResult preview=getPreivewSettings(fileList,request); msg.setInitialPreview(preview.getInitialPreview()); msg.setInitialPreviewConfig(preview.getInitialPreviewConfig()); msg.setFileIds(preview.getFileIds()); return msg; } //删除某一项文件 @RequestMapping(value="/delete",method = RequestMethod.POST) @ResponseBody public Result delete(String id,HttpServletRequest request){ SysFile sysFile=uploaderService.get(SysFile.class,id); String dirPath=request.getRealPath("https://www.jb51.net/"); FileUtil.delFile(dirPath+uploaderPath+File.separator+sysFile.getSavedName()); uploaderService.delete(sysFile); return new Result(); } /** * 获取字体图标map,base-file控件使用 */ @RequestMapping(value="/icons",method = RequestMethod.POST) @ResponseBody public Map getIcons(){ return fileIconMap; } /** * 根据文件名获取icon * @param fileName 文件 * @return */ public String getFileIcon(String fileName){ String ext= StrUtil.getExtName(fileName); return fileIconMap.get(ext)==null?fileIconMap.get("default").toString():fileIconMap.get(ext).toString(); } /** * 根据附件IDS 获取文件 * @param fileIds * @param request * @return */ @RequestMapping(value="/getFiles",method = RequestMethod.POST) @ResponseBody public FileResult getFiles(String fileIds,HttpServletRequest request){ String[] fileIdArr=fileIds.split(","); DetachedCriteria criteria=DetachedCriteria.forClass(SysFile.class); criteria.add(Restrictions.in("id",fileIdArr)); criteria.addOrder(Order.asc("createDateTime")); List<SysFile> fileList=uploaderService.findByCriteria(criteria); return getPreivewSettings(fileList,request); } /** * 回填已有文件的缩略图 * @param fileList 文件列表 * @param request * @return initialPreiview initialPreviewConfig fileIds */ public FileResult getPreivewSettings(List<SysFile> fileList,HttpServletRequest request){ FileResult fileResult=new FileResult(); List<String> previews=new ArrayList<>(); List<FileResult.PreviewConfig> previewConfigs=new ArrayList<>(); //缓存当前的文件 String dirPath = request.getRealPath("https://www.jb51.net/"); String[] fileArr=new String[fileList.size()]; int index=0; for (SysFile sysFile : fileList) { //上传后预览 TODO 该预览样式暂时不支持theme:explorer的样式,后续可以再次扩展 //如果其他文件可预览txt、xml、html、pdf等 可在此配置 if(FileUtil.isImage(dirPath+uploaderPath+File.separator+sysFile.getSavedName())) { previews.add("<img src='." + sysFile.getFilePath().replace(File.separator, "https://www.jb51.net/") + "' " + "style='width:auto;height:160px' alt='" + sysFile.getFileName() + " title='" + sysFile.getFileName() + "''>"); }else{ previews.add("<div><div>" + "<span>"+getFileIcon(sysFile.getFileName())+"</span></div></div>"); } //上传后预览配置 FileResult.PreviewConfig previewConfig=new FileResult.PreviewConfig(); previewConfig.setWidth("120px"); previewConfig.setCaption(sysFile.getFileName()); previewConfig.setKey(sysFile.getId()); // previewConfig.setUrl(request.getContextPath()+"/file/delete"); previewConfig.setExtra(new FileResult.PreviewConfig.Extra(sysFile.getId())); previewConfig.setSize(sysFile.getFileSize()); previewConfigs.add(previewConfig); fileArr[index++]=sysFile.getId(); } fileResult.setInitialPreview(previews); fileResult.setInitialPreviewConfig(previewConfigs); fileResult.setFileIds(StrUtil.join(fileArr)); return fileResult; } }
总结
本文源码已在AdminEAP框架(一个基于AdminLTE的Java开发平台)中开源,可在Github下载相关代码: