Spring MVC返回BLOB类型的图片

来源:互联网 发布:英语教师网络研修心得 编辑:程序博客网 时间:2024/06/08 16:32

项目中有个表专门用来存用户的头像,以BLOB类型存储,然后通过mybatis读取数据,通过Spring MVC以流的形式返回到前台去:




后端代码:


package com.gz.medicine.yun.common.controller;import com.gz.medicine.common.util.ValidateWithException;import com.gz.medicine.yun.common.bean.FromBlob;import com.gz.medicine.yun.common.mapper.FromBlobMapper;import org.apache.commons.lang.StringUtils;import org.apache.log4j.Logger;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.*;/** * @version V1.0 * @Author fendo * @ClassName ImagesController * @PackageName com.gz.medicine.yun.common.controller * @Description 图片 controller * @Data 2017-08-21 10:08 **/@RequestMapping("images")@Controllerpublic class ImagesController extends ValidateWithException {    public static final Logger LOGGER = Logger.getLogger(ImagesController.class);    @Autowired    FromBlobMapper fromBlobMapper;    /**     *     *@Title getIcons     *@Description: 把本地的图片以流的形式输出到页面中去     *@Author fendo     *@Date 2017年8月17日 上午10:52     *@param     *@return void     *@throws     *@测试地址: localhost:8996/GZ/images/geticons     */    @RequestMapping(value="geticons",method = RequestMethod.GET)    public void getIcons(HttpServletRequest request, HttpServletResponse response) {        try {            FileInputStream is = new FileInputStream("G:\\images\\Icon\\valid.png");            int i = is.available(); // 得到文件大小            byte data[] = new byte[i];            is.read(data); // 读数据            is.close();            response.setContentType("image/*"); // 设置返回的文件类型            OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象            toClient.write(data); // 输出数据            toClient.close();        } catch (Exception e) {            e.printStackTrace();        }    }    /**     *     *@Title getImages     *@Description: 根据用户表的的imgguid去FORMBLOB中获取图片     *@Author fendo     *@Date 2017年8月17日 上午10:52     *@param guid     *@return void     *@throws     *@测试地址: localhost:8996/GZ/images/getimages?guid=269A037ADE14FE02E050AE0AC684ADFB     */    @RequestMapping(value="getimages",method = RequestMethod.GET)    public void getImages(String guid,HttpServletRequest request, HttpServletResponse response){        ServletOutputStream out = null;        if(StringUtils.isNotBlank(guid)){            try {                //根据id去图片表获取数据                FromBlob fromBlob = fromBlobMapper.selectByPrimaryKey(guid);                //获取blob字段                byte[] contents = fromBlob.getBdata();                System.out.println("内容是:"+contents.length);                InputStream is = new ByteArrayInputStream(contents);                response.setContentType("image/*");                out = response.getOutputStream();                int len=0;                byte[]buf=new byte[1024];                while((len=is.read(buf,0,1024))!=-1){                    out.write(buf, 0, len);                }                out.flush();                out.close();            } catch (IOException e) {                LOGGER.error(e);                e.printStackTrace();            }        }    }}


实体类:


    private String guid;    private String grdid;    private String sytid;    private Date crtdat;    private String fileurl;    private String filename;    private String formguid;    private byte[] bdata;


BLOB类型的用byte[]来存储!!


前台页面:


<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>测试</title></head><body><!-- 获取id为1的blob类型图片,定义宽128,高185 --><img src="<%=request.getContextPath()%>/images/getimages?guid=269A037ADE14FE02E050AE0AC684ADFB" width="128" height="185"/><hr><img src="<%=request.getContextPath()%>/images/geticons" /></body></html>


效果如下:





通过AJAX调用如下:


<%--  Created by IntelliJ IDEA.  User: fendo  Date: 2017/8/22  Time: 13:16  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>测试</title>    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>    <script>        $(function () {            var xhr = new XMLHttpRequest();            xhr.open("get", "<%=request.getContextPath()%>/images/getimages?guid=5041BB6BB47520F0E053AA0012ACC24D", true);            xhr.responseType = "blob";            xhr.onload = function() {                if (this.status == 200) {                    var blob = this.response;                    var img = document.createElement("img");                    img.onload = function(e) {                        window.URL.revokeObjectURL(img.src);                    };                    img.src = window.URL.createObjectURL(blob);                    img.width=100;                    img.height=100;                    $("#insertImages").html(img);                } }            xhr.send();        })    </script></head><body><!-- 获取id为1的blob类型图片,定义宽128,高185 --><img src="<%=request.getContextPath()%>/images/getimages?guid=5041BB6BB47520F0E053AA0012ACC24D" width="128" height="185"/><div id="insertImages"></div><hr><img src="<%=request.getContextPath()%>/images/geticons" /></body></html>



阅读全文
1 0
原创粉丝点击