原创 

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

分类:java    579人阅读    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("文件预览失败!");
        }
    }
}


支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

 工具推荐 更多»