上传下载工具类

    xiaoxiao2023-10-20  156

    package com.yss.acs.todo.controller; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.DefaultFileItemFactory; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.yss.acs.common.controller.BaseController; import com.yss.acs.common.exception.ACSBaseException; import com.yss.acs.todo.biz.ServiceAreaBO; import com.yss.acs.todo.vo.SerAreaFileUpload; import com.yss.acs.todo.vo.ServiceArea; import com.yss.sofa.framework.biz.BizException; import com.yss.sofa.framework.context.SOFAContext; import com.yss.sofa.framework.log.SOFALogger; import com.yss.sofa.framework.log.SOFALoggerFactory; import com.yss.sofa.framework.util.DateUtil; import com.yss.sofa.framework.web.util.AJAXUtil; import com.yss.sofa.framework.web.util.JSONUtil; import com.yss.sofa.framework.web.util.Page; /** * 文件下载上传、批量下载、zip压缩、遍历文件夹中的文件等工具类 */ @Controller @RequestMapping("/serviceArea") public class ServiceAreaController { // 默认的初始目录 public final static String INIT_PATH = "X:\\sofa_home\\serviceareafile"; // poc服务器 //public final static String INIT_PATH = "/MW-Binary/IBM/WebSphere/sofa_home/serviceareafile"; // 文件上传操作的文件最大限制 public final static long FILE_MAX_SIZE = 1024 * 1024 * 50L; // 2G,下载文件大小的控制 public final static long FILE_SIZE_DOWN = 1024 * 1024 * 1024 * 2L; private SOFALogger log = SOFALoggerFactory.getSOFALogger(ServiceAreaController.class); private ServiceAreaBO serviceAreaBO; @Autowired public ServiceAreaController(ServiceAreaBO serviceAreaBO){ // 设置VO类名 super("com.yss.acs.todo.vo.ServiceArea"); // 设置管理列表页 this.setListView("servicearea_list"); // 设置功能编码,不设置功能编码时系统根据本组件的web应用上下文和列表页面名(listView变量值)拼接 this.setFunctionCode("acs-todo@serviceArea"); this.serviceAreaBO = serviceAreaBO; // 设置父类BO引用 this.setGenericCRUDBO(serviceAreaBO); } /** * 通过文件名查找已经上传的文件 * * @param response 响应 * @param request 请求 * @throws ACSBaseException 异常 */ @SuppressWarnings("unchecked") @RequestMapping(params = "method=findByFileName") public void findByFileName(HttpServletResponse response,HttpServletRequest request) throws Exception{ String fileName = request.getParameter("fileName"); List<SerAreaFileUpload> list = serviceAreaBO.findByFileName(fileName); AJAXUtil.success(response,JSONUtil.toJson(list)); } /** * 遍历目录下所有文件名 * * @return */ public List<ServiceArea> getAllFile(){ File file = new File(INIT_PATH); List<ServiceArea> fileList = new ArrayList<ServiceArea>(); if(file.isDirectory()){ File[] fileArr = file.listFiles(); for(File fileTemp : fileArr){ if(!fileTemp.isHidden()){ ServiceArea serviceArea = new ServiceArea(); serviceArea.setName(fileTemp.getName()); try{ serviceArea.setPath(fileTemp.getCanonicalPath().replace("\\","\\\\")); }catch(IOException e){ log.error("所给路径不是文件目录!"); } serviceArea.setDeleted(false); serviceArea.setMarkDeleteTime(new Date()); fileList.add(serviceArea); } } } return fileList; } /** * 根据路径遍历文件,并判断文件是否逻辑删除,再存入List, * * @param request * @param response * @throws BizException */ @SuppressWarnings({"rawtypes","unchecked"}) @RequestMapping(params = "method=queryFile") public void queryFile(HttpServletRequest request,HttpServletResponse response) throws BizException{ String flag = request.getParameter("pageFlag"); try{ request.setCharacterEncoding("UTF-8"); // 遍历文件夹的文件 List<ServiceArea> fileList = getAllFile(); // 查询数据库中记录的已经逻辑删除的文件 List<ServiceArea> delFile = serviceAreaBO.queryDelfile(); // 进行比较,移除 for(int i = 0; i < delFile.size(); i++){ delFile.get(i); for(int j = 0; j < fileList.size(); j++){ if(delFile.get(i).getName().equals(fileList.get(j).getName())){ fileList.remove(j); } } } Page page = new Page(); page.setData(fileList); if("1".equals(flag)){ page.setRowCount(10); page.setStartRow(1); page.setTotal(fileList.size()); } AJAXUtil.success(response,JSONUtil.toJson(page)); }catch(Exception e){ AJAXUtil.failure(response,e.getMessage()); } } /** * 上传文件 * * @param request * @param response * @throws BizException */ @SuppressWarnings("rawtypes") @RequestMapping(params = "method=uploadFile") public void uploadFile(HttpServletRequest request,HttpServletResponse response) throws BizException{ //String contextPath = request.getContextPath(); //String uploadFilePath = request.getScheme() + "://" + request.getServerName() + ":" // + request.getServerPort() + contextPath + "/uploadfile"; //String realPath = request.getSession().getServletContext().getRealPath("/"); //int b = realPath.indexOf("work"); //String c = realPath.substring(1,b) + "stage/com.yss.acs.todo.jar/resources/uploadtempfile"; PrintWriter pw = null; String version = request.getParameter("fileVersion"); String desc = request.getParameter("fileDesc"); try{ int maxsize = 5 * 4096000;// 20M response.setContentType("text/html;charset=UTF-8"); pw = response.getWriter(); int filesize = request.getContentLength(); if(filesize > maxsize){ throw new BizException("上传文件不能超过" + maxsize + "Kb!"); } File tempfile = new File(System.getProperty("java.io.tmpdir"));// 采用系统临时文件目录 DefaultFileItemFactory diskFileItemFactory = new DefaultFileItemFactory(); diskFileItemFactory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb diskFileItemFactory.setRepository(tempfile); // 设置缓冲区目录 ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setSizeMax(maxsize); //获得文件本身的信息,如存放位置。名字等 List fileItems = servletFileUpload.parseRequest(request); Iterator iterator = fileItems.iterator(); String uploadPath = INIT_PATH; List<FileItem> fileList = new ArrayList<FileItem>();// 上传文件 while(iterator.hasNext()){ FileItem fi = (FileItem)iterator.next(); if(fi.isFormField()){ if("uploadPath".equals(fi.getFieldName().trim())){ uploadPath = fi.getString("UTF-8"); } }else{ if(fi.getName() != null){ fileList.add(fi); } } } // 保存文件 for(FileItem fileItem : fileList){ //文件名称的数组 String[] fileNameTemp = fileItem.getName().replace("\\","/").split("/"); File saveFile = new File(uploadPath + File.separator + fileNameTemp[fileNameTemp.length - 1]); // File uploadfile = new File(realPath); fileItem.write(saveFile); SerAreaFileUpload fileUpload = new SerAreaFileUpload(); fileUpload.setName(saveFile.getName()); fileUpload.setPath(saveFile.getCanonicalPath()); fileUpload.setOperateTime(new Date()); fileUpload.setDesc(desc); fileUpload.setVersion(version); fileUpload.setOperateUserId(SOFAContext.getInstance().getUserId()); serviceAreaBO.save(fileUpload); } pw.write("上传成功!"); }catch(Exception e){ if(pw != null){ pw.write(e.getLocalizedMessage()); return; } }finally{ if(pw != null){ pw.flush(); pw.close(); } } } /** * 下载文件 * * @param request * @param response * @throws BizException */ @RequestMapping(params = "method=downloadFile") public void downloadFile(HttpServletRequest request,HttpServletResponse response) throws BizException{ BufferedInputStream br = null; OutputStream out = null; try{ String filePath = request.getParameter("downloadPath"); File f = new File(filePath); if(!f.exists()){ throw new BizException("文件不存在!"); } br = new BufferedInputStream(new FileInputStream(f)); byte[] buf = new byte[1024]; int len = 0; String fileName = new String((f.getName()).getBytes("GB2312"),"iso8859-1"); response.reset(); response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition","attachment; filename=" + fileName); out = response.getOutputStream(); while((len = br.read(buf)) > 0){ out.write(buf,0,len); } }catch(Exception e){ AJAXUtil.failure(response,e.getMessage()); return; }finally{ try{ if(br != null){ br.close(); } if(out != null){ out.close(); } }catch(IOException e){ AJAXUtil.failure(response,e.getMessage()); } } } /** * 删除文件,删除文件时,在数据库中插入一条删除记录。 * * @param request * @param response * @throws BizException */ @RequestMapping(params = "method=delFiles") public void delFiles(String serviceArea,HttpServletRequest request,HttpServletResponse response) throws BizException{ String serviceAreaData = request.getParameter("serviceArea"); // String path= request.getParameter("path"); SOFAContext context = SOFAContext.getInstance(); String userId = context.getUserId(); // String serviceAreaData = String.valueOf(formMap.get("serviceArea")); List<ServiceArea> list = (List<ServiceArea>)JSONUtil.toList(serviceAreaData,ServiceArea.class); for(ServiceArea vo : list){ vo.setDeleteUserId(userId); vo.setDeleted(true); vo.setMarkDeleteTime(new Date()); } serviceAreaBO.save(list); AJAXUtil.success(response,"删除成功!"); } /** * 下载多个文件,按照文件结构打成zip包 * * @author linht * @param request * @param response * @throws BizException */ @RequestMapping(params = "method=downloadSelectedFiles") public void downloadSelectedFiles(HttpServletRequest request,HttpServletResponse response) throws BizException{ // 初始化文件总大小 long size = 0L; FileInputStream fis = null; FileOutputStream fos = null; BufferedInputStream br = null; OutputStream out = null; ZipOutputStream zipOut = null; File zipFile = null; try{ String filePaths = request.getParameter("downloadPaths"); String[] filePathArr = filePaths.split(","); String tempPath = System.getProperty("java.io.tmpdir").replace("\\","/"); String zipFilePath = tempPath + "/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date()) + ".zip"; log.info("临时路径==" + zipFilePath); try{ // 获取zip压缩文件 zipFile = new File(zipFilePath); fos = new FileOutputStream(zipFile); zipOut = new ZipOutputStream(fos); zipOut.setEncoding("GBK"); File[] fileArr = new File[filePathArr.length]; // 计算检查所要下载文件的大小 for(int i = 0; i < fileArr.length; i++){ fileArr[i] = new File(filePathArr[i]); size += getFileSize(fileArr[i],FILE_SIZE_DOWN); if(size > FILE_SIZE_DOWN){ String exceptionString = "所下载文件大小之和大于限制值,不允许下载"; log.error(exceptionString); throw new BizException(exceptionString); } } log.info("内容压缩之前总大小:(KB)==" + size); // 压缩文件 for(int i = 0; i < fileArr.length; i++){ fileArr[i] = new File(filePathArr[i]); this.getZip(zipOut,fileArr[i],fileArr[i].getName());// 递归压缩方法 } }catch(FileNotFoundException e1){ log.error("文件不存在",e1); AJAXUtil.failure(response,"文件不存在: " + e1.getMessage()); }catch(IOException e1){ log.error("IO异常",e1); AJAXUtil.failure(response,"IO异常:" + e1.getMessage()); }finally{ if(zipOut != null){ zipOut.close();// 提前关闭 (压缩结束) } if(fos != null){ fos.close(); } } fis = new FileInputStream(zipFile); br = new BufferedInputStream(fis); byte[] buf = new byte[1024]; int len = 0; String fileName = new String((zipFile.getName()).getBytes("GB2312"),"iso8859-1"); response.reset(); response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition","attachment; filename=" + fileName); out = response.getOutputStream(); while((len = br.read(buf)) > 0){ out.write(buf,0,len); } }catch(FileNotFoundException e){ log.error("文件没有找到",e); }catch(UnsupportedEncodingException e){ log.error("不支持的编码格式",e); }catch(IOException e){ log.error("IO异常",e); }finally{ try{ if(br != null){ br.close(); } if(fis != null){ fis.close(); } if(out != null){ out.close(); } if(zipFile != null && zipFile.exists()){ zipFile.delete();// 删除缓存的压缩文件 } }catch(IOException e){ AJAXUtil.failure(response,e.getMessage()); } } } /** * 从ZipUtil复制过来的递归压缩方法 * * @param out * @param f * @param baseString * @throws IOExceptio */ private void getZip(ZipOutputStream out,File f,String baseString) throws IOException{ FileInputStream in = null; try{ if(f.isDirectory()){ // 如果是文件夹,则获取下面的所有文件 File[] fl = f.listFiles(); out.putNextEntry(new ZipEntry(baseString + "/"));// 此处要将文件写到文件夹中只用在文件名前加"/"再加文件夹名 String str = baseString.length() == 0?"":baseString + "/"; for(int i = 0; i < fl.length; i++){ getZip(out,fl[i],str + fl[i].getName()); } }else{ // 如果是文件,则压缩 out.putNextEntry(new ZipEntry(baseString)); // 生成下一个压缩节点 in = new FileInputStream(f); byte[] buf = new byte[4096]; int b; while((b = in.read(buf)) != -1){ out.write(buf,0,b); // 写入到压缩包 out.flush(); } } }catch(FileNotFoundException e){ log.error("文件没有找到",e); }finally{ if(in != null){ in.close(); } } } /** * 获得文件或者文件夹内所有文件大小的方法,并会根据max大小进行提示 * * @param file 要判断大小的文件或者文件夹 * @param max 文件或者文件夹限制的最大长度 * @return 大小 * @throws BizException 超出规定大小或者异常时抛出 */ private long getFileSize(File file,long max) throws BizException{ try{ if(!file.exists()){ String exceptionString = "文件[" + file.getCanonicalPath() + "]不存在,请核实后再操作"; log.error(exceptionString); throw new BizException(exceptionString); } if(file.isDirectory()){ long size = 0L; File[] files = file.listFiles(); for(int i = 0; i < files.length; i++){ size += getFileSize(files[i],max); if(size > max){ String exceptionString = "所下载文件大小之和大于限制值,不允许下载"; log.error(exceptionString); throw new BizException(exceptionString); } } return size; }else if(file.isFile()){ if(file.length() > max){ String exceptionString = "文件[" + file.getCanonicalPath() + "]大小大于限制值,不允许下载"; log.error(exceptionString); throw new BizException(exceptionString); } return file.length(); } }catch(IOException e){ log.error("IO异常",e); } throw new BizException("无法识别的文件或文件夹"); } /** * 将文件复制到临时目录 * * @param request * @param response */ @RequestMapping(params = "method=copeFile") public void copeFile(HttpServletRequest request,HttpServletResponse response){ FileInputStream input = null; FileOutputStream output = null; BufferedInputStream inBuff = null; BufferedOutputStream outBuff = null; try{ String fileName = request.getParameter("name"); // 文件扩展名 String extendName = fileName.substring(fileName.indexOf(".")); // 上传文件目录 String initPath = INIT_PATH + "\\" + fileName; File f = new File(initPath); if(!f.exists()){ f.createNewFile(); } log.info("<---------选中在线浏览文件名:" + initPath + "--------->"); input = new FileInputStream(f); inBuff = new BufferedInputStream(input); // 获取项目临时文件 String realPath = request.getSession().getServletContext().getRealPath("/"); // 临时文件夹 String newFileName = new Date().getTime() + extendName; String copyPath = realPath.substring(1) + "download/tempfile/" + newFileName; log.info("<----------临时文件目录:" + copyPath + "---------->"); File copeFile = new File(copyPath); File parentFile = copeFile.getParentFile(); if(!parentFile.exists()){ parentFile.mkdirs(); } if(copeFile.exists()){ copeFile.delete(); } output = new FileOutputStream(copeFile); outBuff = new BufferedOutputStream(output); if(!f.exists()){ throw new BizException("文件不存在!"); } byte[] buf = new byte[1024]; int len = 0; while((len = inBuff.read(buf)) != -1){ outBuff.write(buf,0,len); } outBuff.flush(); AJAXUtil.success(response,newFileName); }catch(Exception e){ AJAXUtil.failure(response,e.getMessage()); return; }finally{ try{ if(inBuff != null){ inBuff.close(); } if(outBuff != null){ outBuff.close(); } }catch(IOException e){ AJAXUtil.failure(response,e.getMessage()); } } } /** * 防止访问中文文件乱码,进行临时文件名修改 * * @param request * @param response */ @RequestMapping(params = "method=updateFileName") public void updateFileName(HttpServletRequest request,HttpServletResponse response){ String oldName = request.getParameter("oldName"); String fileName = request.getParameter("fileName"); int index = fileName.lastIndexOf("."); String Suffix = fileName.substring(index,fileName.length()); String[] path = oldName.split(fileName); String newPath = path[0] + "tempfile" + Suffix; File f = new File(oldName); f.renameTo(new File(newPath)); AJAXUtil.success(response,"tempfile" + Suffix); } /** * 查看后删除文件 * * @param request * @param response */ @RequestMapping(params = "method=removeTempFile") public void removeTempFile(HttpServletRequest request,HttpServletResponse response){ String tempPath = request.getParameter("copyPath"); String realPath = request.getSession().getServletContext().getRealPath("/"); String fileName = realPath.substring(1) + "download/tempfile/" + tempPath; File f = new File(fileName); f.delete(); } @RequestMapping(value = "/tt") public void test(HttpServletRequest request, HttpServletResponse response){ String realPath2 = request.getSession().getServletContext().getRealPath("/"); String dateStr = DateUtil.dateToString(new Date(),"yyyyMMdd"); log.info(dateStr); log.info("realPath2: " + realPath2); } }
    最新回复(0)