【java】 将服务器上文件夹上所有文件打包并下载

功能要求:教师端要将学生上传的报告按班级进行打包下载。

前台HTML如下:

<td align="right">
  <button class="layui-btn layui-btn-sm" data-toggle="modal" 
    onclick="downloadAllAttachment()">
    <i class="layui-icon">&#xe601;</i> 下载全部附件
  </button>
</td> 
 

JS部分通过ajax发送请求到后台的downloadAllAttachment()函数为如下:

function downloadAllAttachment() {
       
        $.ajax({
            type : 'get',
            data:{
                "courseId":getUrlParam("courseId"),
                "teacherId":getUrlParam("teacherId"),
                "theClassId":getUrlParam("theClassId"),
                "taskId": getUrlParam("taskId")
            },
            url : "/summaryRecord/downloadAllAttachment",
            success : function(data) {
               if(data == "文件下载出错") {
               layer.msg("文件下载出错了!",{icon:2});
               }else {
                   var url= '../../resources/SummaryRecord/'+data;
                   location.href=url;
               }
            }
        });
    }

 后台Controller中的方法:

@RequestMapping(value = "/downloadAllAttachment",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "教师端下载所有学生的报告附件")
    public String downloadAllAttachment(String courseId, String teacherId, String theClassId, String taskId,HttpServletRequest request, HttpServletResponse response ) throws Exception {
        String filePath = filesPath+"/SummaryRecord/"+teacherId+"/"+courseId+"/"+taskId+"/"+theClassId;
       String zipPath =  FileUtil.downloadAllAttachment(filePath,request,response);
        zipPath = zipPath.substring(zipPath.indexOf(teacherId));
       return  zipPath;
    }

 FIleUtil的方法将打包压缩后的文件路径返回给前台,从而实现点击下载的功能。注意:每次在该方法中要先判断一下该压缩文件是不是已经存在,如果已经存在则进行删除,然后在继续打包进行压缩,这样做是为了避免在上一次打包和这一次打包的时候有学生提交新的报告。具体的代码如下:


//以下为老师打包下载全部学生的报告
	public static String downloadAllAttachment(String filePath, HttpServletRequest request, HttpServletResponse response) throws Exception {
		File dirFile = new File(filePath) ;
		ArrayList<String> allFilePath = Dir(dirFile);
		List<File> filesList = new ArrayList<>();

		File[] files=new File[allFilePath.size()];
		String path;
		for (int j = 0; j < allFilePath.size(); j++) {
			path=allFilePath.get(j);
			File file = new File(path);
			files[j]=file;
			filesList.add(file);
		}
		return	downLoadFiles(filesList,filePath,request,response);

	}

	//获取文件夹下的所有文件的路径
	public static ArrayList<String> Dir(File dirFile) throws Exception {
		ArrayList<String> dirStrArr = new ArrayList<String>();
		if (dirFile.exists()) {
			//直接取出利用listFiles()把当前路径下的所有文件夹、文件存放到一个文件数组
			File files[] = dirFile.listFiles();
			for (File file : files) {
				//如果传递过来的参数dirFile是以文件分隔符,也就是/或者\结尾,则如此构造
				if (dirFile.getPath().endsWith(File.separator)) {
					dirStrArr.add(dirFile.getPath() + file.getName());
				} else {
					//否则,如果没有文件分隔符,则补上一个文件分隔符,再加上文件名,才是路径
					dirStrArr.add(dirFile.getPath() + File.separator
							+ file.getName());
				}
			}
		}
		return dirStrArr;
	}

	//下载文件
	public static String downLoadFiles(List<File> files,String filePath ,HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
          //这里的文件你可以自定义是.rar还是.zip
			filePath = filePath+"教学班全部附件.zip";
			File file = new File(filePath);
			if (!file.exists()){
				file.createNewFile();
			}else{
				//如果压缩包已经存在则删除后重新打包压缩
				file.delete();
			}
			response.reset();
			//创建文件输出流
			FileOutputStream fous = new FileOutputStream(file);
			/**打包的方法用到ZipOutputStream这样一个输出流,所以这里把输出流转换一下*/
			ZipOutputStream zipOut = new ZipOutputStream(fous);
			/**这个方法接受的就是一个所要打包文件的集合,还有一个ZipOutputStream*/
			zipFiles(files, zipOut);
			zipOut.close();
			fous.close();
			//SummaryRecord/2/3/1536360821177/2018教学班全部附件.zip
			return filePath;

		}catch (Exception e) {
			e.printStackTrace();
			//return "文件下载出错" ;
		}
		return "文件下载出错";
	}

	//把接受的全部文件打成压缩包
	public static void zipFiles(List files,ZipOutputStream outputStream) {

		int size = files.size();

		for(int i = 0; i < size; i++) {

			File file = (File) files.get(i);

			zipFile(file, outputStream);
		}
	}

	//将单个文件打包
	public static void zipFile(File inputFile,ZipOutputStream ouputStream) {

		try {
			if (inputFile.exists()) {
				if (inputFile.isFile()) {
					FileInputStream IN = new FileInputStream(inputFile);
					BufferedInputStream bins = new BufferedInputStream(IN, 512);
					//org.apache.tools.zip.ZipEntry
					ZipEntry entry = new ZipEntry(inputFile.getName());
					ouputStream.putNextEntry(entry);
					// 向压缩文件中输出数据
					int nNumber;
					byte[] buffer = new byte[512];
					while ((nNumber = bins.read(buffer)) != -1) {
						ouputStream.write(buffer, 0, nNumber);
					}
					//关闭创建的流对象
					bins.close();
					IN.close();
				} else {
					try {
						File[] files = inputFile.listFiles();
						for (int i = 0; i < files.length; i++) {
							zipFile(files[i], ouputStream);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

 

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值