Java存储图像的几种方式(前端layui)

前端背景:

前端使用layui,后端接收到一个upload类型的对象

@RequestParam(value = "file", required = false) MultipartFile upload

HTML代码:

JS代码:

layui.use(['upload', 'element', 'layer'], function() {
   var $ = layui.jquery
        , upload = layui.upload
        , element = layui.element
        , layer = layui.layer;

    //, url: '../user/uploadKsPicReg' //改成您自己的上传接口
    //, url: 'http://192.168.122.197:8080/image/uploadStuPic'//这是cuikai的
    var uploadInst = upload.render({
        elem: '#upd1'
        , url: '../user/uploadKsPicReg'
        , acceptMime: 'image/jpg'
        , size: "512"
        , accept: "images"
        , exts: 'jpg'
        , multiple: false
        ,data:{
            sfzh: function () {
                return sfzh;
            }
        }
        , before: function (obj) {
            //预读本地文件示例,不支持ie8
            obj.preview(function (index, file, result) {
                imgSrc = result; //图片链接(base64)
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.resCode !== '0') {
                $("#img1").attr("src", "../assets/img/default_pic.jpg");
                return layer.msg(res.msg);
            }
            $.ajax({
                url: "../user/getKsZpBySfzh?rnt=" + Math.random(),
                async: false,
                type: "POST",
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify($('#form1').serializeJSON()),
                dataType: "json",
                success: function (res) {
                    if (res.resCode !== "0") {
                        layer.alert(res.msg);
                    } else {
                        //回显照片
                        $("#img1").attr("src", "data:image/png;base64,"+res.zpxx);
                        $("#xczp").attr("src", "data:image/png;base64,"+res.zpxx);
                        $('#zpzt').html("已上传");
                        layer.alert("上传成功!");
                        //$("#fileName").val(res.filename);
                    }
                },
                error: function (e) {
                    layer.alert("处理异常返回!" + e);
                }
            });

        }
        , error: function () {
            //演示失败状态,并实现重传
            var demoText = $('#yczText1');
            demoText.html('上传失败 重试');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });
});

后端

怎么把图像以base64存放在数据库存中

使用java.util.Base64类

String s = java.util.Base64.getEncoder().encodeToString(upload.getBytes());

将这个字符串保存在类据库中即可,注意数据类型不要用nvarchar用varchar

nvarchar的最大值是4000,varchar最大值是8000
varchar能存储的字节数就是它的长度,nvarchar能存储的字节数是它的长度乘2

如何读取呢?

业务和SQL部分就是读取一个字符串,主要是前端:
将返回的Base64作一下拼接,放在图片的src上即可。

$("#xczp").attr("src", "data:image/png;base64,"+res.zpPath);

怎么把图像以image类型存放在sqlserver数据库中

这个办法比较简单,将字节数组直接放在要执行sql的HashMap中即可。

HashMap map = new HashMap();
map.put("id",id);
map.put("photo",upload.getBytes());

然后在sql中这样写#{photo,jdbcType=BLOB},我用的是MyBatis


	insert into t_photo (id,photo) values(#{id},#{photo,jdbcType=BLOB})

如何读取呢?

返回一个Object即可。


然后在业务层将其转成byte数组,再由byte数组转成Base64,前端展现方式和上面一样。

blobBytes  = (byte[])userService.getPhotoById(id);
if(blobBytes!=null){
	zpxx64 = Base64.getEncoder().encodeToString(blobBytes);
}

将图像以文件的形式存放在文件服务器中

这个是最中规中矩的办法

	   //文件路径
       String imgPath = memoryUtil.getXtcs("KSTXDZ");//这是在数据库定义的全体图像路径文件夹
       String tempPath = "/now/";//详细的业务名简称
       String path = imgPath + tempPath;
       File file = new File(path);
       String filename = "";
       if (!file.exists()) {
           file.mkdirs();
       }
       if (upload != null) {
           filename = "photo_" + id + ".jpg";//跟据业务来定图像名称
           try {
               upload.transferTo(new File(file, filename));//这个upload是layui传递的对象
           } catch (IllegalStateException | IOException e) {
               logger.error(e.toString(), e);
               resMap.put("resCode", "99");
               resMap.put("msg", "上传图片失败!");//固定格式的返回参数
               return resMap;
           }
       } else {
           resMap.put("resCode", "99");
           resMap.put("msg", "没有图片!");
           return resMap;
       }

如何读取图像呢?

这里不再作过多解释,稍作修改直接用即可。

@RequestMapping(value = "/getImg/now", method = RequestMethod.GET)
@ResponseBody
public String getStuImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
    byte[] img;
    String path = request.getServletContext().getRealPath("/assets/img") + "/default_pic.jpg";
    File file = new File(path);//创建文件对象
    String imgPath = memoryUtil.getXtcs("KSTXDZ");
    String id= request.getParameter("id");
    File now = new File(imgPath + "/now/" + id+ ".jpg");//创建文件对象
    if (now.exists()) {
        file = now;
    }
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");
    OutputStream os = null;
    InputStream inputStream = null;
    try {
        String picType = ImgUtil.getPicType(new FileInputStream(file));
        response.setContentType("image/" + picType);
        inputStream = new FileInputStream(file);//创建字节输出流对象
        byte[] buffer = new byte[4096];
        os = response.getOutputStream();
        int i = 0;
        int sum = 0;
        while ((i = inputStream.read(buffer)) != -1) {
            //写文件流
            os.write(buffer, 0, i);
            sum += i;
        }
        response.setContentLength(sum);
        os.flush();
        os.close();
        inputStream.close();//关闭字节流
    } catch (Exception e) {
        logger.error("图片加载", e);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return "success";
}

你可能感兴趣的:(前端,后端,实用工具,java,layui)