JAVA通过文件路径下载文件

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Author wulianfa
 * @Description 文件下载工具类
 * @Date 9:09 2019.05.17
 */
@Slf4j
public class FileDownLoadUtil {

    /**
     * 通过文件路径下载文件
     *
     * @param filePath 文件路径
     * @param response
     * @throws Exception
     */
    public static void download(String filePath, HttpServletResponse response) throws Exception {
        // 判断文件是否存在
        File file = new File(filePath);
        log.info("DOWNLOAD PATH:" + filePath);
        if (!file.exists() || file.isDirectory()) {
            log.info("FILE DOES NOT EXIST!");
            return;
        }
        // 自定义文件名
        String filename = file.getAbsolutePath();
        String suffix = filename.substring(filename.lastIndexOf("."));
        //根据UUID重命名文件
        String attachmentName = IdUtils.getId() + suffix;
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(attachmentName, "UTF-8"));
        InputStream in = null;
        BufferedInputStream bis = null;
        OutputStream out = null;
        BufferedOutputStream bos = null;
        try {
            in = new FileInputStream(filePath);
            bis = new BufferedInputStream(in);
            byte[] data = new byte[1024];
            int bytes = 0;
            out = response.getOutputStream();
            bos = new BufferedOutputStream(out);
            while ((bytes = bis.read(data, 0, data.length)) != -1) {
                bos.write(data, 0, bytes);
            }
            bos.flush();
        } catch (Exception e) {
            log.error("THE REQUEST FAILED:" + e.getMessage(), e);
            throw new Exception("THE REQUEST FAILED!");
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (out != null) {
                    out.close();
                }
                if (bis != null) {
                    bis.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

 

你可能感兴趣的:(JAVA通过文件路径下载文件)