hjr-JAVA 关于文件上传与解压与excel导出

  <form method="post" action="url"
        <input type="file" name="uploadFile"/>
        <br/><br/>
        <input type="submit" value="上传"/>
    </form>

上述前端是一个最简单的上传框

后端用springmvc举例

  public BaseResultForm uploadLog(HttpServletRequest request, @RequestParam("uploadFile") CommonsMultipartFile uploadFile) {
        String fileName = uploadFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);//后缀
    	InputStream inputStream = null;
        inputStream = uploadFile.getInputStream();
}

上述代码就可以获取到上传文件流了

之后我们可以对上传的文件做操作了

  • 比如传到第三方文件服务去,如阿里的oss,使用工具类,设置好传参即可上传下载

  • 比如另存到项目路径里

        String projectPath = request.getServletContext().getRealPath("/");//此处为项目target/root 路径
也可以存储到"D://upload/"等路径

            File fileMakeDir = new File(projectPath + "/日志转换/" + randomFileName + "/source");
  if (!fileMakeDir.exists()) {
                fileMakeDir.mkdirs();
            }
             InputStream inputStream = null;
            os = new FileOutputStream(fileMakeDir.getPath() + "/" + randomFileName + ".txt");
         inputStream = uploadFile.getInputStream();
           int bytes = 0;
          while ((bytes = inputStream.read()) != -1) { //读取文件
              os.write(bytes);
       }
          os.flush(); //关闭流
         inputStream.close();
          os.close();
         //上述代码可以实现把上传的输入流另存到一个路径

下面写几个工具方法

    //获取某路径下的全部文件 
    public void getFiles(String path, List<File> fileList) {
        File file = new File(path);
        File[] files = file.listFiles();
        for (File fileIndex : files) {
            if (!fileIndex.exists()) {
                throw new NullPointerException("Cannot find " + fileIndex);
            } else if (fileIndex.isFile()) {
                fileList.add(fileIndex);
            } else {
                if (fileIndex.isDirectory()) {
                    getXmlFiles(fileIndex.getAbsolutePath(), fileList);
                }
            }
        }
    }



 //解压zip文件
    public static void unZipFiles(File zipFile, String descDir) throws IOException {
        ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));//解决中文文件夹乱码
        String name = zip.getName().substring(zip.getName().lastIndexOf('\\') + 1, zip.getName().lastIndexOf('.'));

        File pathFile = new File(descDir + name);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }

        for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements(); ) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String zipEntryName = entry.getName();
            InputStream in = zip.getInputStream(entry);
            String outPath = (descDir + name + "/" + zipEntryName).replaceAll("\\*", "/");

            // 判断路径是否存在,不存在则创建文件路径
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if (!file.exists()) {
                file.mkdirs();
            }
            // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if (new File(outPath).isDirectory()) {
                continue;
            }
            // 输出文件路径信息
//			System.out.println(outPath);

            FileOutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            in.close();
            out.close();
        }
        System.out.println("******************解压完毕********************");
        return;
    }


//移除某个文件夹下全部文件
    private static void removeDir(File dir) {
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                removeDir(file);
            } else {
                System.out.println(file + ":" + file.delete());
            }
        }
        System.out.println(dir + ":" + dir.delete());
    }

一般都是使用线程池处理文件的后续操作

 ExecutorService cacheThreadPool = Executors.newCachedThreadPool();
      
        Runnable runnable = new DoQualityCheck(projectPath, randomFileName, ossDir, qualityCheckLog, qualityCheckDao, qualityCheckLogMapper);
                cacheThreadPool.execute(runnable);//加入到线程池,会自动执行

class XXXimplements Runnable {
        private String projectPath;
        public XXX(String projectPathr) {
        }

        @Override
        public void run() {
            logger.info("开启新线程===========================================");
  
        }
    }

有时要把数据导出到excel

 @RequestMapping(method = RequestMethod.GET, value = "exportExcel")
    public void exportExcel(HttpServletResponse response) {
        try {
            List<XXX> XXX= new ArrayList<>();
    
            HSSFWorkbook workbook = new HSSFWorkbook();//创建Excel对象
//创建多个sheet
            HSSFSheet sheet = null;
            HSSFRow row;
            HSSFCell cell;
            int maxSheetRowCount = 10000;
            int sheetIndex = 1;//记录额外创建的sheet数量
            for (int i = 0; i < qualityCheckDTOList.size(); i++) {
                int rowIndexInSheet = i % maxSheetRowCount + 1;// rowIndexInSheet = 0 标题行; 实际数据从rowIndexInSheet = 1开始
                if (rowIndexInSheet == 1) {
                    sheet = workbook.createSheet("xxx");//创建工作表单
                    row = sheet.createRow(0);
                  
                        cell = row.createCell(0);
                        cell.setCellValue("xxx");
                
                    sheetIndex++;
                }
                row = sheet.createRow(rowIndexInSheet);
            		cell = row.createCell(0);
                    cell.setCellValue("xxx");
         
                cell = row.createCell(1);
  				cell.setCellValue("xxx");

     
            }
            OutputStream output = response.getOutputStream();
            String new_filename = URLEncoder.encode("xxx" + xxx, "UTF-8");
            // 此处使用utf8编码
            String rtn = "filename=\"" + new_filename + "\"" + ".xls";
            response.addHeader("Content-Disposition", "attachment;" + rtn);
            workbook.write(output);
            output.flush();
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章