通过servlet下载本地文件(单文件与多文件下载)

这篇博客介绍如何通过Servlet实现从服务器下载本地文件,包括单个文件下载和多个文件打包成zip下载。首先,通过点击按钮获取选中的文件路径,然后根据路径调用Servlet进行下载操作。在Servlet中,设置了跨域访问支持,并处理了中文文件名乱码问题,对于单文件下载直接读取文件流并写入响应,多文件则创建zip压缩包后再下载。

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

//下载
    	$("#download").click(function(){
    		var obj = document.getElementsByName("filecheck");//获取所有checkbox
    		var check_val = [];
    		for(k in obj){
		        if(obj[k].checked){//所有选中的checkbox
		            check_val.push(obj[k].value);
		        }
		    }
		    if(check_val.length==1){//单文件下载
		    	window.location.href=parent.window.globedataserverurl + "/DownLoadFile?filepath="+check_val[0];
		    }else{//多文件下载
		    	window.location.href=parent.window.globedataserverurl + "/BatchDownFile?filepath="+check_val.join();//将数组转为字符串
		    }
    		
    	});

package com.globe.servlet;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 文件下载
 */
@WebServlet("/DownLoadFile")
public class DownLoadFile extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String basePath="E:/FTP/武汉局FTP";
       
    public DownLoadFile() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 支持跨域访问
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		String filepath  = request.getParameter("filepath");
		filepath = new String(filepath.getBytes("ISO-8859-1"), "UTF-8");//处理请求参数路乱码
		File file = new File(basePath+filepath);
		//判断文件是否存在
		if(file.exists()){
			response.setContentType("application/x-msdownload");
            String filename=URLEncoder.encode(file.getName(),"utf-8"); //解决中文文件名下载后乱码的问题
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);//设置文件下载名
            
            FileInputStream fis=new FileInputStream(file);
            BufferedInputStream bis=new BufferedInputStream(fis);
            ServletOutputStream sos=response.getOutputStream();
            int size=0;
            byte[] b=new byte[1024];
            while ((size=bis.read(b))!=-1) {
            	sos.write(b, 0, size);
            }
            sos.flush();
            sos.close();
            bis.close();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}

package com.globe.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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

/**
 * 批量文件下载
 */
@WebServlet("/BatchDownFile")
public class BatchDownFile extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String basePath="E:/FTP/武汉局FTP";
       
    public BatchDownFile() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 支持跨域访问
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		response.setContentType("application/x-msdownload");
		response.setHeader("Content-Disposition", "attachment;filename=files.zip");
		
		String filepaths  = request.getParameter("filepath");
		filepaths = new String(filepaths.getBytes("ISO-8859-1"), "UTF-8");//处理请求参数路乱码
		String[] filepath = filepaths.split(",");

		/*将要下载的文件打包成zip再下载*/
        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
        for(String filename : filepath){
        	File file = new File(basePath + filename);
        	if(file.exists()){
				zos.putNextEntry(new ZipEntry(file.getName()));//压缩包内文件名
				FileInputStream fis = new FileInputStream(file);
				int size = 0;
	            byte b[] = new byte[1024];
	            while((size = fis.read(b)) != -1){
	                zos.write(b, 0, size);
	            }
	            fis.close();
        	} 
        }
        zos.flush();
        zos.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值