JAVA 单个或多个下载服务器上带超链接的文件 并压缩后下载

注:这里下载的文件是服务器上的文件,即:http://192.16.80.94/wav/20150625/48/20150625140223_48_8003_8002_to_18064000047.wav 这种类型文件 而不是像别的例子是在本地获取文件的绝对或相对路径

以下的代码是我在实际项目中遇到的情形。如有错误地方,请多多指教....................


以下是java代码

package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * @author:  daiyichang
 * @Description:  带链接单个文件下载、多个文件批量打包再下载  ,注:文件地址是服务器上的
 *   eg:http://172.16.10.24/recordwav/20150625/48/20150625140223_48_8003_8002_to_18064000047.wav
 * @date:  2015-7-24
 * @version: 
 */
public class BatchDownload extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static	Logger log = Logger.getLogger(BatchDownload.class);

	public BatchDownload() {
		super();
	}
	
	/**
	 * 生成zip包的名称  这里是以当前时间为zip文件名
	 * @return
	 */
	private String getZipFilename() {
		Date date = new Date();
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		String zipName=format.format(date.getTime())+ ".zip";
		return zipName;
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		try {
			//获取index.jsp页面hidden的值
			String param=request.getParameter("paramValue");
			
			if("1".equals(param)){//多个文件压缩后下载
				log.info("多个文件压缩后下载----------------------------");
				response.setContentType("APPLICATION/OCTET-STREAM");
				response.setHeader("Content-Disposition", "attachment; filename=" + this.getZipFilename());
				
				String wav="http://127.0.0.1:8080/LoadingDemo/20150522111534_35_8002_8002_to_015618587456.wav";
				String img="http://127.0.0.1:8080/LoadingDemo/gaoxiu.jpg";
				ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
				
				//放入需下载文件地址
				String[] strs ={wav,img};
				
				zipFile(strs, "", zos);
				zos.flush();
				zos.close();
			}else if("2".equals(param)){
				log.info("一个文件直接下载----------------------------");
				downloadOnedFile(request, response);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	/**
	 *  单个文件下载 注:这里指的是超链接文件下载
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void  downloadOnedFile(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		
	     String filePath="http://127.0.0.1:8080/LoadingDemo/20150522111534_35_8002_8002_to_015618587456.wav";
		 
	     log.info("===文件路径=====================>"+filePath);
		 String fileName = filePath.substring(filePath.lastIndexOf("/")+1);//下载文件时显示的文件保存名称 
	     log.info("===文件名=====================>"+fileName);
	     
	     response.setContentType("application/x-download");
	     response.setHeader("Content-disposition", "attachment;filename="+ fileName);
	    
		
	    InputStream in = null;
		OutputStream outp = null;
		try {
			URL url = new URL(filePath);		
			URLConnection conn = url.openConnection();
			in = conn.getInputStream();
			outp = response.getOutputStream();

			byte[] b = new byte[1024];
			int i = 0;
			while ((i = in.read(b)) > 0) {
				outp.write(b, 0, i);
			}
			outp.flush();
		} catch (Exception e) {
			log.error("录音下载时发生异常:" ,e);
			e.printStackTrace();
		} finally {
			if (in != null) {
				in.close();
				in = null;
			}
			 if(outp != null){
	            outp.close();
	            outp = null;
	        }
		}
	}

	/**
	 * 压缩文件
	 * @param strs   文件地址数组
	 * @param baseName   zip文件前缀名称
	 * @param zos   zip输出流
	 * @throws IOException
	 */
	private void zipFile(String[] strs, String baseName, ZipOutputStream zos)
			throws IOException {
		for (int i = 0; i < strs.length; i++) { 
			URL url = new URL(strs[i]);	
			
			URLConnection conn = url.openConnection();
			InputStream in = conn.getInputStream();
			String fileName = strs[i].substring(strs[i].lastIndexOf("/")+1);//下载文件时显示的文件保存名称 
			
			zos.putNextEntry(new ZipEntry(fileName));
			byte[] buffer = new byte[1024];
			int r = 0;
			while ((r = in.read(buffer)) != -1) {
				zos.write(buffer, 0, r);
			}
			in.close();
		}
	}

	

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
}
以下是jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
      <form action="zipDownload.do" method="post">
      		<input type="hidden" name="paramValue" value="1"/>
			<input type="submit" value="下载"/>
		</form>
  </body>
</html>

以下是web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>	
  <servlet>
    <servlet-name>imgZipDownload</servlet-name>
    <servlet-class>test.BatchDownload</servlet-class>
  </servlet>
 

  <servlet-mapping>  
    <servlet-name>imgZipDownload</servlet-name>
    <url-pattern>/zipDownload.do</url-pattern>
  </servlet-mapping>

  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

源码下载地址:http://download.csdn.net/detail/lianwuya/8930493



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值