原创 

JAVA WEB 或spring 中附件下载文件和在浏览器中打开文件模式设置

分类:java    511人阅读    IT小君  2021-08-17 21:17
/**
* 附件下载方式放回
**/
public static void downloadFile(String fileName, InputStream inputStream, HttpServletResponse response) throws IOException, BusinessServiceException
{
    if(inputStream != null)
    {
        ServletOutputStream os = response.getOutputStream();
        try(BufferedInputStream bis = new BufferedInputStream(inputStream); BufferedOutputStream bos = new BufferedOutputStream(os))
        {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download;");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            int length;
            byte[] bytes = new byte[2048];
            while(-1 != (length = bis.read(bytes)))
            {
                bos.write(bytes, 0, length);
            }
        }
        catch(IOException e)
        {
            log.error("download exception:", e);
            throw new BusinessServiceException("下载文件失败!");
        }
    }
}

/**
* 浏览器中打开预览方式
**/
public static void previewFile(String fileName, InputStream inputStream, HttpServletResponse response) throws IOException, BusinessServiceException
{
    if(inputStream != null)
    {
        ServletOutputStream os = response.getOutputStream();
        try(BufferedInputStream bis = new BufferedInputStream(inputStream); BufferedOutputStream bos = new BufferedOutputStream(os))
        {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("image/png");
            response.setHeader("Content-Disposition", "inline;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            int length;
            byte[] bytes = new byte[2048];
            while(-1 != (length = bis.read(bytes)))
            {
                bos.write(bytes, 0, length);
            }
        }
        catch(IOException e)
        {
            log.error("previewFile exception:", e);
            throw new BusinessServiceException("文件预览失败!");
        }
    }
}


点击广告,支持我们为你提供更好的服务

html5 svg夜空中星星流星动画场景特效

HTML5 Canvas竖直流动线条背景动画特效

html5图标下拉搜索框自动匹配代码

HTML5数字产品服务公司网站模板

jQuery右端悬浮带返回顶部特效

css鼠标跟随文字模糊特效

小众时尚单品在线电子商务网站模板

canvas炫酷鼠标移动文字粒子特效

响应式时尚单品在线商城网站模板

有机水果蔬菜HTML5网站模板

html5 canvas进度条圆环图表统计动画特效

js+css3抽奖转盘旋转点餐代码

html5 canvas彩色碎片组合球形旋转动画特效

网页设计开发公司网站模板

css+js实现的颜色渐变数字时钟动画特效

现代时尚家具公司网站模板

响应式咖啡饮品宣传网站模板

响应式太阳能能源公司网站模板

中小型创意设计服务公司网站模板

HTML5现代家居装潢公司网站模板

点击广告,支持我们为你提供更好的服务
 工具推荐 更多»
点击广告,支持我们为你提供更好的服务