前台通过base64传图片到后台的实现方法

3 篇文章 0 订阅

前台将图片转换为base64的方法如下:

$("#article_image").change(function(){
    var file = this.files[0];
        //判断类型是不是图片  
        if(!/image\/\w+/.test(file.type)){     
                alert("请确保文件为图像类型");   
                return false;   
        }   
        var reader = new FileReader();   
        reader.readAsDataURL(file);   
        reader.onload = function(e){
          image_base64=this.result.split(",")[1];
           //就是base64 
          article_image = image_base64;   
        }
  });

后台代码接受base64的值,转换为图片后存储返回存储的url

 @RequestMapping(value = "/uploadPoster.do")  
    public @ResponseBody Object uploadPoster(HttpServletRequest request,  
                HttpServletResponse response) throws Exception {  
            HttpJson httpJson = new HttpJson();  
            System.out.println("开始上传照片");  
             String customerId = request.getParameter("computecustomerId");  
            String ret_fileName = null;// 返回给前端已修改的图片名称  
            String base64Img = request.getParameter("base64");  
            // 临时文件路径  
            //String dirTemp = "\\upload\\temp";  
            String dirTemp = "\\upload";  
            String uploadImg = "\\upload";  
  
            try {  
                request.setCharacterEncoding("UTF-8");  
            } catch (UnsupportedEncodingException e1) {  
                // TODO Auto-generated catch block  
                e1.printStackTrace();  
                httpJson.setMsg("上传图片失败");  
                httpJson.setSuccess(false);  
                return httpJson;  
            }  
            // response.setContentType("text/html; charset=UTF-8");  
            // PrintWriter out = response.getWriter();  
  
            String realPath = request.getServletContext().getRealPath("");  
            String tempPath = request.getServletContext().getRealPath("/")  
                    + dirTemp;  
            File file_normer = new File(realPath + uploadImg+"/"+customerId);  
            if (!file_normer.exists()) {  
                file_normer.mkdirs();  
            }  
            // 用于设置图片过大,存入临时文件  
            DiskFileItemFactory factory = new DiskFileItemFactory();  
            factory.setSizeThreshold(20 * 1024 * 1024); // 设定使用内存超过5M时,将产生临时文件并存储于临时目录中。  
            factory.setRepository(new File(tempPath)); // 设定存储临时文件的目录。  
  
            ServletFileUpload upload = new ServletFileUpload(factory);  
            upload.setHeaderEncoding("UTF-8");  
             if (base64Img == null) // 图像数据为空    
                    return false;    
             base64Img = base64Img.replaceAll("data:image/jpeg;base64,", "");    
                BASE64Decoder decoder = new BASE64Decoder();    
                try {    
                    // Base64解码    
                    byte[] b = decoder.decodeBuffer(base64Img);    
                    for (int i = 0; i < b.length; ++i) {    
                        if (b[i] < 0) {// 调整异常数据    
                            b[i] += 256;    
                        }    
                    }    
                    // 生成jpeg图片    
                    ret_fileName = new String((DateHandler.dateToStr(new Date(),"yyyyMMddhhmmss")+".jpg").getBytes("gb2312"), "ISO8859-1" ) ;   
                    File file = new File(realPath + uploadImg+"/"+ customerId + "/" + ret_fileName);  
                    OutputStream out = new FileOutputStream(file);    
                    out.write(b);    
                    out.flush();    
                    out.close();    
                } catch (Exception e) {    
                    e.printStackTrace();    
                }    
              
                String image_url = request.getSession().getServletContext() .getContextPath()+ "/upload/" + customerId + "/" + ret_fileName;  
            // 将已修改的图片url对应的id返回前端  
            httpJson.setMsg("上传图片成功");  
            httpJson.setSuccess(true);  
            httpJson.setObj(image_url);  
            return JSONObject.fromObject(httpJson);  
           }  
      
        }  

17级徐朝晖 2017年3月16日

  • 2
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值