ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

base64图片上传及回显

2022-05-24 10:32:27  阅读:108  来源: 互联网

标签:function 回显 base64 result var import 上传 图片


base64图片上传及回显

后端

base64工具类

package com.autumn.util;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;

public class Base64Util {
    public static boolean GenerateImage(String imgData, String filePath, String fileName) throws IOException {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        boolean b = true;
        try {
            imgData = imgData.split(";base64,")[1];
            File dir = new File(filePath);
            if (!dir.exists()) {//判断文件目录是否存在
                dir.mkdirs();
            }
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bfile = decoder.decodeBuffer(imgData);
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
            b = false;
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return b;
    }


    public static String GetImageStr(String imgFile) {//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e)  {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串  
    }

}

UploadController

package com.autumn.common.controller;

import com.gmtx.util.Base64Util;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * UploadBase64Controller
 * @author: 秋雨
 * 2022-05-14 11:14
 **/

@Controller
@RequestMapping(value = "/front/uploadbase64", method = { RequestMethod.GET, RequestMethod.POST })
public class UploadBase64Controller {

    /**
     * 上传base64图片到服务器
     */
    @RequestMapping(value = "/uploadimg", method = {
            RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Map uploadimg(@RequestParam("content") String imgbase64,
                            HttpServletRequest req, HttpServletResponse resp)
            throws UnsupportedEncodingException, IOException{
        String a=imgbase64;
        imgbase64=imgbase64.replaceAll("@", "+");
        String fileName = UUID.randomUUID().toString() + ".jpg";
        String filePath = "/upload";

        boolean b = Base64Util.GenerateImage(imgbase64, req.getRealPath("/") + filePath, fileName);
        if(b)
        {
            imgbase64=filePath+"/"+fileName;
        }
        else
        {
            imgbase64="";
        }
        Map result = new HashMap();
        result.put("code", b?"success":"fail");
        result.put("imgurl", imgbase64);
        result.put("message", b?"成功!":"失败!");
        return result;
    }
}

前端

文件上传


    /**
     * 图片上传到服务器
     */
    function upload(content){
        var imgurl='';
        var loading = weui.loading('图片上传中...');
        $.ajax({
            type: "POST",
            dataType: "json",
            async:false,
            url: "../../../front/uploadbase64/uploadimg",
            data: {
                content:content
            },
            success: function(data) {
                loading.hide();
                if(data.code == "success") {
                    imgurl = data.imgurl;
                } else {
                    weui.alert("上传失败,请重新上传。");
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                loading.hide();
                weui.alert("图片文件过大,请上传截屏后的图片。");
            }
        });
        return imgurl;
    }

    /**
     * 图片转base64
     * - 回调函数中调用upload上传图片函数
     */
    function fileTobase64(imgDom,upload,callbacksetkey) {
        var html = "<li class=\"weui-uploader__file\" style=\"background-image: url('"+ window.URL.createObjectURL(imgDom.files[0])+ "')\"></li>";
        //显示图片
        $(imgDom).parent().parent().children("ul").append(html);
        //获取图片对象
        var fileObj = imgDom.files[0];
        var result_base64 = '';
        //图片转为base64
        if (fileObj.size / 1024 > 1024) { //大于1M,进行压缩上传
            var loading = weui.loading('图片压缩中...');
            /*压缩图片*/
            result_base64 = photoCompress(
                fileObj,
                {
                    quality : 0.5
                },
                function(base64Codes) {
                    //替换base64字符串里的+号
                    base64Codes = base64Codes.replace(/\+/g,"@");
                    //去除=
                    if (base64Codes.indexOf("=") > 0) {
                        base64Codes = base64Codes.substring(0,base64Codes.indexOf("="));
                    }
                    loading.hide();

                    result_base64 = base64Codes;  //返回最终base64
                    var resultImgURL = upload(result_base64);
                    callbacksetkey(resultImgURL);
                });

        } else {  //如果图片为1M以内
            //直接用FileReader.readAsDataURL读取成base64
            var reader = new FileReader();
            reader.onload = function(e) {
                var imgBase64 = e.target.result;
                imgBase64 = imgBase64.replace(/\+/g,"@");  //把base64的+改为@
                if (imgBase64.indexOf("=") > 0) {
                    imgBase64 = imgBase64.substring(0,imgBase64.indexOf("="));  //去掉=号
                }
                result_base64 = imgBase64;  //返回最终base64
                var resultImgURL = upload(result_base64);
                key = resultImgURL;
                callbacksetkey(resultImgURL);
            }
            reader.readAsDataURL(imgDom.files[0]);
        }

    }

    $(function () {

    /*土地证上传*/
    $("#landcertificatepath").change(function(){
        fileTobase64(this,upload,function(imgURL){
            if(landcertificatepath == null || landcertificatepath == undefined || landcertificatepath == ''){
                landcertificatepath = imgURL;
            }else{
                landcertificatepath += (","+imgURL);
            }
            /*提交更新土地证*/
            submitInfo("landcertificatepath",landcertificatepath);
        });
    });

    });
<form id="formApply" style="margin-left: 10px;">
    <div class="weui-uploader__bd">
        <ul class="weui-uploader__files" id="divboxlandcertificatepath" ulforname="landcertificatepath">
        </ul>

        <div class="weui-uploader__input-box">
            <input id="landcertificatepath" class="weui-uploader__input"
                   type="file" accept="image/*" multiple required
                   emptyTips="请重传" />
        </div>
    </div>
</form>

回显

$.ajax({
    type: "POST",
    dataType: "json",
    url: "../../../front/apply/selectOneById",
    data: {
        accountid:'q2'
    },
    async:false,
    success: function(jsondata) {
        APPLYID = jsondata.id;
        $('#id').val(jsondata.id);
        $('#accountid').val(jsondata.accountid);

        /*多图片回显*/
        var ulArr=$("#formApply ul");
        /*遍历ul*/
        $.each(ulArr,function(index,object){
            /*先获取ul的name属性*/
            var ulName = $(object).attr("ulforname");
            /*根据name去json中获取对应的值-逗号分割的字符串*/
            var ulVal = jsondata[ulName];

            /*把所有的name属性变为全局变量,值为返回的值*/
            window[ulName] = ulVal;
            /*图片回显*/
            if(ulVal != null && ulVal != undefined && ulVal != ""){
                var imgArr = ulVal.split(",");
                for(var i=0;i<imgArr.length;i++){
                    var imgPath = "../../../"+decodeURI(imgArr[i]);
                    $("#formApply ul[ulforname="+ulName+"]").append("<li class=\"weui-uploader__file\" style=\"background-image: url('"+ imgPath + "')\"></li>");
                }
            }
        });


    },
    error: function(jqXHR, textStatus, errorThrown) {
        showcontent("数据获取异常!");
    }
});

标签:function,回显,base64,result,var,import,上传,图片
来源: https://www.cnblogs.com/aeolian/p/16304557.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有