基于layui框架,实现从jsp页面上传图片到数据库,熟悉layui框架才能用。

首先如何上传图片。

java 图片写入excel java实现图片上传到数据库_上传

 

这里为layui   的js 部分和 html

var uploadInst = upload.render({
                elem: '#uploadBtn'  //上传按钮的id
                ,accept: 'images' // 上传文件的类型
                ,auto: false
                ,size: 1024 * 1024 * 2 //上传文件的最大 大小 这里为2M
                ,choose: function(obj){
                    //预读本地文件示例,不支持ie8
                    //当用户点击上传并选好图片之后,将图片转为base64格式
                   obj.preview(function(index, file, result){
                    //直接将img的src属性值 转为base64 立即显示在右侧
                        $('#faceImg').attr('src', result); //图片链接(base64)
                       //将隐藏域中的值改为base64传给后台
                        $(":hidden[name=face]").val(result);
                    });
                }
           ; })

  

<label class="layui-form-label">头像</label>
        <div class="layui-input-block">
            <div class="layui-inline">
                <img style="border-radius:10%; width:200px;height:200px;" onerror="this.src='${ctx}/images/default.jpg'" src="${ctx}/user.do?method=initFace&face=${dbUser.face}" class="layui-upload-img" id="faceImg">
            </div>
            <div>
                <button style="margin-left: 150px" type="button" class="layui-btn" id="uploadBtn">上传头像</button>
            </div>

 当用户点击提交后,会将生成的base64代码,通过隐藏域上传后Controller层中,然后再调用pojo类,用User对象的setFace 方法将base64存储起来。

这时候在跳转到service中,调用如下方法处理base64

private String uploadFace(String face) {
        //获取到base64中,图片的后缀
        int index1 = face.indexOf("/") + 1;
        int index2 = face.indexOf(";");
        String hz = face.substring(index1, index2);
        //拼接好,图片的名称
        String fileName = "d:/fileUpdate/" + UUID.randomUUID().toString() + "." + hz;
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream os = null;
        try {
            //截取base64中的正文主体部分
            byte[] bytes = decoder.decodeBuffer(face.substring(face.indexOf(",") + 1));
            File file = new File(fileName);
       //这里会通过fileName,在对应的路径中创建这个图片
            file.createNewFile();
            os = new FileOutputStream(file);
            os.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
     //将fileName返回出去。然后存储在数据库中
        return fileName;
    }

  到这里就将图片上传做好了,接下来就是读取图片

onerror="this.src='${ctx}/images/default.jpg'" src="${ctx}/user.do?method=initFace&face=${dbUser.face}"

上面这段代码为img 的属性, onerror 为当src找不到对应路径时显示的图片。即默认初始化的头像

当页面加载时,会通过src 去访问servlet。 将当前登陆对象的face属性(face为图片路径)传到servlet中。然后调用initFace方法通过路径显示图片

private void initFace(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        //url传值中获取到头像的路径
        String facePath = request.getParameter("face");
        //路径
        File file = new File(facePath);
        if(!file.exists()){
            return;
        }
        InputStream is =  null;
        OutputStream os = null;

        try {
            is = new FileInputStream(file);
            os = response.getOutputStream();
            byte[] b = new byte[1024*10];
            // 正常返回读到的数据个数, 没有了就返回-1
            int len = 0;
            while((len = is.read(b))!=-1){
                os.write(b,0,len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }