结合springmvc,使用ajax上传base64图片数据

2016-12-26 19:18:47来源:CSDN作者:javaloveiphone人点击

一、前端:

<input type="file" id="myImage" name="myImage"/>  
<script type="text/javascript">      $("#myImage").bind("change",function(){        uploadFile($(this));    });    //通过onChange直接获取base64数据q   function uploadFile(file){        var f = file.files[0];        var reader = new FileReader();        reader.onload = function(){            var data = e.target.result;            if (data.lastIndexOf('data:base64') != -1) {                  data = data.replace('data:base64', 'data:image/jpeg;base64');            } else if (data.lastIndexOf('data:,') != -1) {                  data = data.replace('data:,', 'data:image/jpeg;base64,');            }            if(isCanvasSupported()){            }else{                alert("您的浏览器不支持");            }        };        reader.onerror = function(){            console.log("上传失败了 ");        }        reader.readAsDataURL(f);    }    //ajax异步上传    function ajaxUploadBase64File(base64Data){        var url = window.location.protocol + '//' + window.location.host + "/register/uploadBase64";        $.ajax({            url:url,            type:"post",            data:{base64Data:base64Data},            dataType:"json",            success:function(data){                if(data.success == true){                    console.log("上传成功");                }else{                    console.log("上传失败");                }            },            error:function(){                console.log("上传失败");            }        });    };     //是否支持canvas    function isCanvasSupported(){        var elem = document.createElement('canvas');        return !!(elem.getContext && elem.getContext('2d'));    };</script>  

二、后台:

    @RequestMapping(value="/uploadBase64",method=RequestMethod.POST)    @ResponseBody    public ActionResult<Map<String,String>> base64UpLoad(@RequestParam String base64Data, HttpServletRequest request, HttpServletResponse response){          ActionResult<Map<String,String>> result = new ActionResult<Map<String,String>>();        try{              logger.debug("上传文件的数据:"+base64Data);            String dataPrix = "";            String data = "";            logger.debug("对数据进行判断");            if(base64Data == null || "".equals(base64Data)){                throw new Exception("上传失败,上传图片数据为空");            }else{                String [] d = base64Data.split("base64,");                if(d != null && d.length == 2){                    dataPrix = d[0];                    data = d[1];                }else{                    throw new Exception("上传失败,数据不合法");                }            }            logger.debug("对数据进行解析,获取文件名和流数据");            String suffix = "";            if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){//data:image/jpeg;base64,base64编码的jpeg图片数据                suffix = ".jpg";            } else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){//data:image/x-icon;base64,base64编码的icon图片数据                suffix = ".ico";            } else if("data:image/gif;".equalsIgnoreCase(dataPrix)){//data:image/gif;base64,base64编码的gif图片数据                suffix = ".gif";            } else if("data:image/png;".equalsIgnoreCase(dataPrix)){//data:image/png;base64,base64编码的png图片数据                suffix = ".png";            }else{                throw new Exception("上传图片格式不合法");            }            String tempFileName = getRandomFileName() + suffix;            logger.debug("生成文件名为:"+tempFileName);            //因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包            byte[] bs = Base64Utils.decodeFromString(data);            try{                //使用apache提供的工具类操作流                FileUtils.writeByteArrayToFile(new File(Global.getConfig(UPLOAD_FILE_PAHT), tempFileName), bs);              }catch(Exception ee){                throw new Exception("上传失败,写入文件失败,"+ee.getMessage());            }            Map<String,String> map =new HashMap<String,String>();               map.put("tempFileName", tempFileName);            result.setResultMessage("上传成功");            result.setData(map);            logger.debug("上传成功");        }catch (Exception e) {              logger.debug("上传失败,"+e.getMessage());            result.setSuccess(false);            result.setResultMessage("上传失败,"+e.getMessage());          }          return result;    }

参考:
Base64编码与图片互转、
JAVA 把base64图片数据转为本地图片、
如何把图片转换成base64在后台转换成图片放在本地

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台