• springBoot优雅返回图片/网页到浏览器


    一、普通spring mvc返回图片或网页到浏览器

    @Controller
    @RequestMapping(value = "/image")
    public class ImageController {
        @RequestMapping(value = "/get")
        @ResponseBody
        public void getImage(HttpServletResponse response) throws IOException {
            File file = new File("D:/test.jpg");
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            
            response.setContentType("image/jpeg");
            OutputStream out = response.getOutputStream();
           out.write(result);
           out.flush();
           //关闭响应输出流
           out.close();
           
        }
    }

    二、spring boot

    import org.springframework.http.MediaType;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
     
    @Controller
    @RequestMapping(value = "/image")
    public class ImageController {
        @RequestMapping(value = "/get",produces = MediaType.IMAGE_JPEG_VALUE)
        @ResponseBody
        public byte[] getImage() throws IOException {
            File file = new File("D:/test.jpg");
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        }
    }

    如果是网页的话,

    produces = MediaType.TEXT_HTML
  • 相关阅读:
    String(Java版本)
    前端工程化开发之yeoman、bower、grunt
    前端自动化开发之grunt
    前端模块化开发之seaJs
    浅谈图片蒙版效果-webkit-mask
    div模拟textarea实现高度自增长
    预加载显示图片的艺术
    轻松实现localStorage本地存储
    利用Navigation Timing测量页面加载时间
    利用jstree插件轻松构建树应用
  • 原文地址:https://www.cnblogs.com/myf008/p/10881780.html
Copyright © 2020-2023  润新知