Spring MVC返回BLOB类型的图片

项目中有个表专门用来存用户的头像,以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")
@Controller
public 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
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值