SpringMvc 下载和批量下载

本文介绍如何使用Java实现单个及多个文件的下载功能,并通过压缩流将多个文件压缩为一个压缩包进行下载的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.单个文件的下载。

 

@RequestMapping("/downLoad")
	public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
		String resourceName = "test.txt";
		File file = new File("D:/"+resourceName);
		HttpHeaders headers = new HttpHeaders();
		String filename = new String(resourceName.getBytes("utf-8"),"iso-8859-1");
		headers.setContentDispositionFormData("attachment", filename);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
	}

2.多个文件的下载

思路:将多个需要下载的文件压缩成1个文件进行下载。

压缩流的使用

String pathname = "D:/test.zip";
		File file = new File(pathname);
		
		/*if(!file.exists()) {
			file.createNewFile();
		}*/
		
		OutputStream out = new FileOutputStream(file);
		ZipOutputStream output = new ZipOutputStream(out);
		
		InputStream in = null;
		
		File temp = new File("D:/test.txt");
		System.out.println(temp.getName());
		
		output.putNextEntry(new ZipEntry(temp.getName()));
		in = new FileInputStream(temp);
		
		
		int i = 0 ;  
        while((i=in.read())!=-1){ // 读取内容  
        	output.write(i) ;    // 压缩输出  
        }  
        in.close() ; // 关闭输入流  
        output.close() ; 

批量下载

//批量文件压缩后下载
	@RequestMapping("/downLoad2")
	public ResponseEntity<byte[]> download2(HttpServletRequest request) throws IOException {
		
		//需要压缩的文件
		List<String> list = new ArrayList<String>();
		list.add("test.txt");
		list.add("test2.txt");
		
		//压缩后的文件
		String resourcesName = "test.zip";
		
		ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream("D:/"+resourcesName));
		InputStream input = null;
		
		for (String str : list) {
			String name = "D:/"+str;
			input = new FileInputStream(new File(name));  
            zipOut.putNextEntry(new ZipEntry(str));  
            int temp = 0;  
            while((temp = input.read()) != -1){  
                zipOut.write(temp);  
            }  
            input.close();
		}
		zipOut.close();
		File file = new File("D:/"+resourcesName);
		HttpHeaders headers = new HttpHeaders();
		String filename = new String(resourcesName.getBytes("utf-8"),"iso-8859-1");
		headers.setContentDispositionFormData("attachment", filename);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
	}

 

 

 

 

 

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值