通过HttpServletResponse对象,实现图片的流方式显示和文件的流方式下载

本文介绍如何在控制器中实现流式图片显示与文件下载的功能,包括设置响应头、创建输入输出流以及使用缓冲区读写数据。同时提供了解决文件名中文乱码的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.图片的流方式显示,在controller中创建以下方法:

public void showImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setContentType("image/jpeg");  
    // 获取图片
    File file = new File("/home/aaa.jpg");  
    // 创建文件输入流  
    FileInputStream is = new FileInputStream(file);  
    // 响应输出流  
    ServletOutputStream out = response.getOutputStream();  
    // 创建缓冲区  
    byte[] buffer = new byte[1024];  
    int len = 0;  
    while ((len = is.read(buffer)) != -1) {  
        out.write(buffer, 0, len);  
    }  
    is.close();  
    out.flush();  
    out.close();
}

页面展示图片的时候,直接在img标签的src属性中调用这个方法:

<img src="/.../showImage.ht" />

2.文件的流方式下载:

public void download(File file, String fileName, HttpServletResponse response) throws IOException{
    if(null != file){
        OutputStream out =null;
        InputStream in = null;
        try{
            in = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[in.available()];
            in.read(buffer);
            response.reset();
            response.setHeader("content-disposition","attachment;filename=" + encodingFileName(fileName));   
            out = new BufferedOutputStream(response.getOutputStream());
            out.write(buffer);
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(null != in){
                in.close();
            }
            if(null != out){
                out.close();
            }
        }
    }
}

//对文件名进行编码,解决下载文件名中文乱码的问题
private static String encodingFileName(String fileName) {
    String returnFileName = "";
    try {
        returnFileName = URLEncoder.encode(fileName, "UTF-8");
        returnFileName = StringUtils.replace(returnFileName, "+", "%20");
        if (returnFileName.length() > 150) {
            returnFileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
            returnFileName = StringUtils.replace(returnFileName, " ", "%20");
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return returnFileName;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值