文件下载工具类

package com.caiex.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;

import com.caiex.exception.DownloadException;
import com.caiex.global.Constants;

/**
 * 文件下载工具类
 * 
 * @author wsy
 *
 */
@Component
public class FileOperateUtil {

    /**
     * 
     * @param response
     *            响应对象 ,用于获取输出流
     * @param fileName
     *            文件名
     * @throws DownloadException
     *             文件不存在或者io异常时抛出此异常
     */
    public static void download(HttpServletResponse response, String fileName) throws DownloadException {

        String downLoadPath = Constants.XLS_DOWNLOAD_PATH + fileName;
        long fileLength = new File(downLoadPath).length();
        response.setContentType("application/octet-stream");
        try {
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
        } catch (UnsupportedEncodingException e) {
        }
        response.setHeader("Content-Length", String.valueOf(fileLength));

        FileInputStream fis = null;
        ServletOutputStream os = null;
        try {
            fis = new FileInputStream(downLoadPath);
            os = response.getOutputStream();
            IOUtils.write(IOUtils.toByteArray(fis), os);
        } catch (FileNotFoundException e) {
            throw new DownloadException("文件未找到");
        } catch (IOException e) {
            throw new DownloadException("io异常");
        } finally {
            IOUtils.closeQuietly(fis);
            IOUtils.closeQuietly(os);
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值