jQuery使用Base64 生成图片预览和java后台不同的接收处理方式

本文主要解决移动或者pc端上传图片及生成预览的问题
1.jQuery 生成base64编码,前台预览
2.jsp 自定义上传按钮两种方式的上传 input file 和 input hidden
3.java后台两种方式的上传操作 SpringMvc自身的上传机制和Base64解码上传的操作

jQuery代码:

<script type="text/javascript">

$(function(){

// 前端只需要给input file绑定这个change事件即可(下面两个方法不需要修改)获取到图片
 $('.testUpload').bind('change',function(event){
     var imageUrl = getObjectURL($(this)[0].files[0]);
     convertImgToBase64(imageUrl, function(base64Img){

        //base64Img为转好的base64,放在img src直接前台展示()
        //alert(base64Img);
        $("#base").attr("src",base64Img);
        //base64转图片不需要base64的前缀data:image/jpg;base64
        //alert(base64Img.split(",")[1]);
         $("#uploadFile").val(base64Img.split(",")[1]);
      });
      event.preventDefault(); 
  }); 

//生成图片的base64编码
function convertImgToBase64(url, callback, outputFormat){ 
     //html5 的convas画布
     var canvas = document.createElement('CANVAS'); 
     var ctx = canvas.getContext('2d'); 
     var img = new Image; 
     img.crossOrigin = 'Anonymous'; 
     img.onload = function(){
       var width = img.width;
       var height = img.height;
       // 按比例压缩4倍
       //var rate = (width
       //原比例生成画布图片
       var rate = 1;
       canvas.width = width*rate; 
       canvas.height = height*rate; 
       ctx.drawImage(img,0,0,width,height,0,0,width*rate,height*rate); 
 // canvas.toDataURL 返回的是一串Base64编码的URL,当然,浏览器自己肯定支持 
        var dataURL = canvas.toDataURL(outputFormat || 'image/png'); 
        callback.call(this, dataURL); 
        canvas = null; 
      };
      img.src = url; 
    }

//createobjecturl()静态方法创建一个包含了DOMString代表参数对象的URL。该url的声明周期是在该窗口中.也就是说创建浏览器创建了一个代表该图片的Url.
function getObjectURL(file) {
     var url = null ; 
      if (window.createObjectURL!=undefined){
     // basic
        url = window.createObjectURL(file) ;
      } else if (window.URL!=undefined){
     // mozilla(firefox)
        url = window.URL.createObjectURL(file) ;
      } else if (window.webkitURL!=undefined){
     //web_kit or chrome
        url = window.webkitURL.createObjectURL(file) ;
      }
      return url ;
     }
 script>

Jsp代码


<form id="uploadImg" method="post" enctype="multipart/form-data" action="${contextPath }/uploadImg.html">
  <div style='position:relative; '>
    <img id="base" style="position: absolute;" alt="上传" src="${contextPath }/img/upload.jpg">
    
    <input type="file" style="position:absolute; opacity:0;"  name="files" class="testUpload">
    
    <input type="hidden"  name="baseFile" id="uploadFile">

  div>
  <div id="subInfo" style="cursor:pointer;margin-left:50px; width: 100px; height: 40px; font-size: 16px; background-color: #2d78f4; color:#FFFFFF; text-align: center; border: 1px solid #2129FB; " >
     <div style="height: 8px;" > div>
            提交
   div>

form>

java代码

@RequestMapping("uploadImg")
public ModelAndView uploadImg(String[] baseFile, HttpServletRequest request) throws IllegalStateException, IOException{

    ModelAndView mav = new ModelAndView();
    mav.setViewName("MyJsp");
    mav.addObject("mes", "Success!!!");

    /**
     * springMvc 上传图片
     * 1.enctype属性的属性值设为multipart/form-data。
     * 2.input的type属性的属性值设为file。
     * 后台就可以使用multipartResolver获取到前台上传的文件
     */
    /*
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
    if(multipartResolver.isMultipart(request)){
        MultipartHttpServletRequest multipertRequest = (MultipartHttpServletRequest)request;
        Iterator iter = multipertRequest.getFileNames();
        //上传一张图片时可以直接使用这个
        //MultipartFile file11 = multipertRequest.getFile("files");
        //上传多张图片
        while (iter.hasNext()) {
            MultipartFile file = multipertRequest.getFile((String)iter.next());
            if(!file.isEmpty()){
                String path = request.getSession().getServletContext().getRealPath("uploadImg");
                String imageName = this.getImageName();
                //File.separator路径分隔符
                File savefile = new File(path+File.separator+imageName);
                //file.transferTo将上传的文件写入指定位置
                file.transferTo(savefile);
                }
            }
    }*/


   /**
    * Base64 上传图片
    */
  String path = request.getSession().getServletContext().getRealPath("uploadImg");
  Base64 base64 =  new Base64();
  String[] imageNames = new String[baseFile.length];
  //file 为前台隐藏域里面的字符串
  if(baseFile!= null && baseFile.length!=0){
      int index = 0;
      for (String base64Str : baseFile) {
        //base64 解码
          byte[] byteArray = base64.decode(base64Str);
          // 调整异常数据  
          for (byte b : byteArray) {
              if(b<0)
                  b+=256;
          }
          String imageName = this.getImageName();
          try {
              OutputStream out = new FileOutputStream(path+File.separator+imageName);
              out.write(byteArray);
              out.close();
          } catch (Exception e) {
              e.printStackTrace();
              System.out.println(imageNames[0]); 
          }
          imageNames[index] = path+File.separator+imageName;
          index ++ ;
      }
  }
      System.out.println(imageNames[0]); 

return mav;
}

/**
  * 根据系统规则得到图片名称
  */
  public String getImageName(){
      return UUID.randomUUID().toString()+".jpg";
  }

你可能感兴趣的:(技术)