java下载本地文件通用公共类

 /**
     * 下载服务器上文件
     *
     * @param httpServletRequest
     * @param response
     * @param name               告知浏览器的文件名
     * @param path               文件路径
     * @return
     * @throws Exception
     */
    public ServletOutputStream downFiletemp(HttpServletRequest httpServletRequest, HttpServletResponse response, String name, String path) throws Exception {

        ServletOutputStream outputStream = null;
        InputStream inputStream = null;
        BufferedInputStream bufferedInputStream = null;
        File file = new File(path);
        //如果不是文件
        if (!file.isFile()) {
            file = new File(path + name);
        }
        //下载显示的文件名,解决中文名称乱码问题
       
        String downloadFielName = null;
        if (httpServletRequest.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
            downloadFielName = new String(name.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器
        } else if (httpServletRequest.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0 ||
                httpServletRequest.getHeader("User-Agent").indexOf("like Gecko") > 0) {
            downloadFielName = URLEncoder.encode(name, "UTF-8");// IE浏览器
        } else if (httpServletRequest.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) {
            downloadFielName = new String(name.getBytes("UTF-8"), "ISO8859-1");// 谷歌
        }
        //
        response.setHeader("Content-Disposition", "attachment; filename=" + downloadFielName);
        outputStream = response.getOutputStream();

        try {
            inputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(inputStream);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = bufferedInputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, bytes.length);
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        } finally {
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (Exception e) {
                   log.info(e.getMessage());
                }
            }
            if (outputStream != null){
                try{
                    outputStream.close();
                }catch (Exception e){

                }
            }

        }
        return outputStream;
    }

你可能感兴趣的:(通用公共类,java,开发语言)