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

20 篇文章 0 订阅
13 篇文章 0 订阅

前端背景:

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

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

HTML代码:

<div class="layui-upload" style="width: 150px" align="center">
   <div class="layui-upload-list">
        <img class="layui-upload-img3" id="img1" src="../assets/img/default_pic.jpg"
             style="width:130px;height:160px;border:1px solid #D2D2D2;">
        <input type="hidden" id="fileName" name="fileName"/>
    </div>
    <button type="button" class="layui-btn layui-btn-normal" id="upd1"
            style="width:120px;" algin="center">上传照片(jpg)
    </button>
</div>

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('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            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 id="insertPhoto" parameterType="java.util.HashMap">
	insert into t_photo (id,photo) values(#{id},#{photo,jdbcType=BLOB})
</insert>

如何读取呢?

返回一个Object即可。

<select id="getPhotoById" parameterType="java.lang.Integer" resultType="java.lang.Object">
	select photo from t_photo where id = #{id}
</select>

然后在业务层将其转成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";
}
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要实现前端layui后端Java实现PDF导出,可以使用以下步骤: 1. 前端使用layui中的表格组件展示需要导出的数据。 2. 前端通过Ajax请求将数据发送到后端,后端使用Java处理数据。 3. 后端使用Java PDF库(如iText)生成PDF文件。 4. 后端将生成的PDF文件发送到前端前端通过浏览器下载即可。 以下是大致的代码实现: 前端代码: ```html <table id="tableData" lay-filter="tableData"></table> <button id="exportBtn" class="layui-btn layui-btn-normal">导出PDF</button> <script> // 初始化表格 layui.use('table', function(){ var table = layui.table; table.render({ elem: '#tableData', url: 'data.json', // 数据接口 cols: [[ {field: 'id', title: 'ID'}, {field: 'name', title: '名称'}, {field: 'price', title: '价格'} ]] }); // 导出按钮点击事件 $('#exportBtn').click(function() { // 获取表格数据 var data = table.cache.tableData; // 发送数据到后端 $.ajax({ type: 'POST', url: '/export/pdf', data: JSON.stringify(data), contentType: 'application/json', success: function(res) { // 下载PDF文件 window.location.href = res.url; } }); }); }); </script> ``` 后端代码: ```java @PostMapping("/export/pdf") public ResponseEntity<Resource> exportPdf(@RequestBody List<Map<String, Object>> data) throws Exception { // 生成PDF文件 ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfDocument pdf = new PdfDocument(new PdfWriter(baos)); Document document = new Document(pdf); Table table = new Table(3); table.addCell(new Cell().add(new Paragraph("ID"))); table.addCell(new Cell().add(new Paragraph("名称"))); table.addCell(new Cell().add(new Paragraph("价格"))); for (Map<String, Object> row : data) { table.addCell(new Cell().add(new Paragraph(row.get("id").toString()))); table.addCell(new Cell().add(new Paragraph(row.get("name").toString()))); table.addCell(new Cell().add(new Paragraph(row.get("price").toString()))); } document.add(table); document.close(); // 构建响应体 ByteArrayResource resource = new ByteArrayResource(baos.toByteArray()); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=data.pdf"); headers.add(HttpHeaders.CONTENT_TYPE, "application/pdf"); return ResponseEntity.ok() .headers(headers) .contentLength(resource.contentLength()) .body(resource); } ``` 注意事项: 1. 要使用iText库,需要在项目中添加对应的依赖,可以在Maven中添加以下依赖: ```xml <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext7-core</artifactId> <version>7.1.15</version> </dependency> ``` 2. 前端需要使用jQuery库和layui框架,需要在HTML文件中添加对应的依赖。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值