文件下载方法

本文介绍了一个Java实现的文件下载工具方法,该方法通过设置HTTP响应头来实现浏览器中文件的下载功能。支持不同文件大小情况下的处理,并确保了资源的正确关闭。

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

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author yl
 *
 */
public class FileDownloadUtil {
    /**
     * <p>
     * 文件下载工具方法
     * </p>
     *
     * @param fileName 文件名
     * @param downloadPath 文件路径
     * @param response
     * @throws Exception
     */
    public static void modelDownload(String fileName, String downloadPath,
            HttpServletResponse response) throws Exception {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            long fileLength = new File(downloadPath).length();

            if(fileLength>0){
                response.setContentType("application/x-msdownload;");
                response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
                response.setHeader("Content-Length", String.valueOf(fileLength));
                
                bis = new BufferedInputStream(new FileInputStream(downloadPath));
                bos = new BufferedOutputStream(response.getOutputStream());
                byte[] buff = new byte[1024];
                int bytesRead;
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }
            }else{
                response.setContentType("application/x-msdownload;");
                response.setHeader("Content-disposition", "attachment; filename=文件不存在!");
                response.setHeader("Content-Length", String.valueOf(fileLength));
                System.out.println("文件不存在!"+downloadPath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值