java基础(三--1)io流之根据路径,将图片以流的形式返给前端

 
  
import java.io.*;
import java.net.URLEncoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @Description:
 * @Param: [url, response, request]
 * @return: void
 * @Author: wcl
 * @Date: 2021/9/16
 */
@RequestMapping("/downloadImgStream")
public static void writeFile( @RequestParam String url,HttpServletResponse response,HttpServletRequest request) throws Exception {
    File file = new File(url);
    // 取得文件名。
    String fileName = file.getName();
    InputStream fis = null;
    fis = new FileInputStream(file);
    request.setCharacterEncoding("UTF-8");
    String agent = request.getHeader("User-Agent").toUpperCase();
    if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1)))
        fileName = URLEncoder.encode(fileName, "UTF-8");
    else {
        fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
    }
    response.setCharacterEncoding("UTF-8");
    response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
    response.setHeader("Content-Length", String.valueOf(file.length()));
    response.setHeader("Pragma", "public");
    response.setHeader("Cache-Control", "public");
    ServletOutputStream out = response.getOutputStream();
    byte[] b = new byte[1024];
    int len;
    while ((len = fis.read(b)) != -1) {
        out.write(b, 0, len);
    }
    response.flushBuffer();
    fis.close();
}

你可能感兴趣的:(java基础,java)