上传图片以base64格式存储进数据库

JSP页面

        <div class="weui_cells weui_cells_form">
            <div class="weui_panel_hd" style="color:#ff6600;" >温馨提示:附件大小不超过1M,附件格式为JPG、PNG、JPEG。div>
          <div id="takePhotoUpId" class="weui_uploader_bd">
            
    class="weui_uploader_files"> <%--
  • class='weui_uploader_file'> <div class='smallimg'>class='weui_icon_clear' style="float:right">div> <div class='divimg' style='width:77px;height:77px;background-size:cover;z-index:999;'> id='photoimgId' class="imgstyle" src="<%=basePath%>resources/css/ynzjy/images/user_img.png" style="width:77px;height:77px;background-size:cover;z-index:999;"onclick="openFile(this,'photoimgId')"> div>
  • --%>
<div class="weui_cell"> <div class="weui_uploader_input_wrp" style=""> id="selectimgId" class="weui_uploader_input" type="button" multiple=""> div> div> div> div>


<div class="footer"> <div style="width: 100%; padding-top: 0px;padding-bottom: 3px;"> <div style="padding-bottom: 5px; float: left; width: 100%; margin-left: 0px;"> "javascript:btnAddContentSaveForm();" class="weui_btn weui_btn_default" style="line-height: 2.83333333;">预  约 div> div> div> div>

JS处理:

/*
调用微信接口
*/
    $.ajax({
        type : "get",
        url : "weixin/sign",
        dataType : "json",
        contentType : "application/json;charse=UTF-8",
        async : true,
        data : {
            "url" : location.href.split('#')[0],
            "tenantId" : "703"
        },
        error : function(request) {

        },
        success : function(result) {
            var timestamp = parseInt(result.timestamp);
            var nonceStr = result.nonceStr;
            var signature = result.signature;
            var appId = result.appId;
             wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: appId, // 必填,公众号的唯一标识
                timestamp: timestamp, // 必填,生成签名的时间戳
                nonceStr: nonceStr, // 必填,生成签名的随机串
                signature: signature,// 必填,签名,见附录1
                jsApiList: ['chooseImage',  
                             'previewImage',  
                             'uploadImage',  
                             'downloadImage',
                             'getLocalImgData'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
            });
        }
    });

    $("#selectimgId").click(function(){
        wx.ready(function () {  
            wx.chooseImage({
                count: 1, // 默认9
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
                success: function (res) {
                    var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
                    var localId = res.localIds[0];
                    if (window.__wxjs_is_wkwebview) {  //判断ios是不是用的 wkwebview 内核
                        wx.getLocalImgData({
                            localId: localId, // 图片的localID
                            success: function (res) {
                                var localData = res.localData; // localData是图片的base64数据,可以用img标签显示
                                localData = localData.replace('jgp', 'jpeg');//iOS 系统里面得到的数据,类型为 image/jgp,因此需要替换一下
                                showSelectImg(localIds,localData);
                            }
                        });
                    }else{
                         wx.getLocalImgData({
                                localId: localId, // 图片的localID
                                success: function (res) {
                                    var localData = "data:image/jpeg;base64,"+res.localData; // localData是图片的base64数据,可以用img标签显示
                                    showSelectImg(localIds,localData);
                                }
                          });
                    }
                    // alert("选择本地获取的值:"+localIds);

                    //alert(localIds);
                    //console.log("chooseImage.localIds:"+localIds);
                }
            });
        });
    });






function addMaterialBtn(data){

    var tenantId = $("#tenantId").val();
    var bzmcl = data;

    var userId = localStorage.getItem("userId");  
    var len = $("#takePhotoUpId .weui_uploader_files").find("li").length;

    var fileli = $("#takePhotoUpId .weui_uploader_files").find("li");

    var imgDataAttr = new Array(); //存储保存的图片数组
    var fd = new FormData(document.forms[0]);
    var num = 0;

    if(fileli.length > 0){

        for ( var j = 0; j < fileli.length; j++) {
            num++;
            var imgdata = $(fileli[j]).find("div.divimg").find(".imgstyle").attr("src");

            var blob = dataURItoBlob(imgdata); // 上一步中的函数
            //alert(blob);
            var canvas = document.createElement('canvas');
            var dataURL = canvas.toDataURL('image/jpeg', 0.5);
            fd.append("file_img"+num, blob, 'image'+num+'.png');
        }

        var urlPath = "weixin/addmaterImgContent?tenantId="+tenantId+"&bzmcl="+bzmcl+"&userId="+userId;

        $.showLoading("提交中,请稍等...");
        $.ajax({  
          url:urlPath,  
    //      type:"post",  
          method: 'POST',
          processData: false, // 必须
          contentType: false, // 必须
          dataType: 'json',
          data: fd,
    //      contentType:"application/x-www-form-urlencoded;charset=UTF-8",
          success:function(data){//回调函数
            $.hideLoading();
            if(data == 1 || data == true || data == "1"){
                $.toast("图片保存成功", function() {
                    history.go(-1);
                });
            }else{
                $.toast("图片保存失败","cancel");
            }

          },
          error:function(errormsg){
              $.hideLoading();
            alert("出现异常错误信息:"+errormsg);
          }
       });  
    }
}



function dataURItoBlob(base64Data) {
    var byteString;
    if (base64Data.split(',')[0].indexOf('base64') >= 0){
        byteString = atob(base64Data.split(',')[1]);
    }else{
        byteString = unescape(base64Data.split(',')[1]);
    }
    var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {type:mimeString});
}

Controller层处理

ontroller层处理
@ResponseBody
@RequestMapping(value="addmaterImgContent")
public void addReportImgContentForm(HttpServletRequest request,
        HttpServletResponse response){
    int result = 0;
    try {
        String tenantId = request.getParameter("tenantId");
        String bzmcl = request.getParameter("bzmcl");
        String userId = request.getParameter("userId");
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile multipartFile = multiRequest.getFile(iter.next());
                if (multipartFile != null) {
                    BdcDjsjfjModel bdcDjsjfjModel = new BdcDjsjfjModel();

// System.out.println(“获取文件内容:” + multipartFile.getOriginalFilename());
String fileUpName = multipartFile.getOriginalFilename();
// photoId = fileUpName.split(“_”)[0];
long fileSize = multipartFile.getSize();
String appSize = FileUtils.convertFileSize(fileSize);

                    BASE64Encoder encoder = new BASE64Encoder();  
                    // 通过base64来转化图片
                    String data = encoder.encode(multipartFile.getBytes());
                    String contentImg = "data:image/jpeg;base64,"+data;
                    bdcDjsjfjModel.setContentimg(contentImg);

// attachModel.setAttachName(fileUpName);
bdcDjsjfjModel.setWjmc(fileUpName);
// System.out.println(“获取的值:”+fileSize);
bdcDjsjfjModel.setWjdx(fileSize+”“);
bdcDjsjfjModel.setWjccfs(“2”);
bdcDjsjfjModel.setUserId(userId);
bdcDjsjfjModel.setWjlx(“.png”);
bdcDjsjfjModel.setBzm_sjcl(bzmcl);
result = bdcDjsjfjService.addBdcDjsjfj(bdcDjsjfjModel);
}
}
}
} catch (Exception e) {
result = 0;
e.printStackTrace();
}
try {
if (result == 1) {
response.getWriter().println(“1”);
} else {
response.getWriter().println(“0”);
}
} catch (Exception e) {
e.printStackTrace();
}
}
“`

你可能感兴趣的:(JAVA)