使用Aajx将Canvas传入后台

来源:互联网 发布:逆战刷枪软件2017 编辑:程序博客网 时间:2024/06/05 22:33
    1:前端代码。    // 获取Canvas的编码。    var imgData = document.getElementById("canvas").toDataURL("image/jpeg");    // 上传到后台。    $.ajax({         type: "post",                url:"$!front_url/uploadImg",         data: {image : imgData},         async: true,         success: function (htmlVal) {               alert("另存图片成功!");         },error: function(data) {               alert(e.responseText); //alert错误信息         }    });

     

     // 2.Java代码, 此代码在后期改为了上传5张图片,循环保存的,大家需要根据自己需求改改就行。

     @RequestMapping(value = "portal/upLoadImage")

     @ResponseBody

    public Object uploadImg(String id, String image1, String image2, String image3, String image4, String image5, HttpServletRequest request, HttpServletResponse response) {


        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        Base64 base64 = new Base64();
        try {
            
            // 获取上传文件的BASE编码。
            String[] imgs = {image1, image2, image3, image4, image5};


            File file = new File(basePath + "/" + id);
            // 判断文件是否存在。
            if(!file.exists()) {
                // 新建文件夹。
                file.mkdirs();
            }


            // 循环保存图片。
            int count = 0;
            List<String> urlList = new ArrayList<String>();
            for (int i = 0; i < imgs.length; i++) {
                if(null != imgs[i]) {
                    byte[] k = base64.decode(imgs[i].substring("data:image/jpeg;base64,".length()));
                    InputStream is = new ByteArrayInputStream(k);
                    String fileName = UUID.randomUUID().toString().replace("-", "");
                    String imgFilePath = basePath + "/" + id + "/" + fileName + ".jpg";
                    BufferedImage imageB = ImageIO.read(is);
                    boolean flag = ImageIO.write(imageB, "jpg", new File(imgFilePath));
                    System.out.println(imgFilePath + " ------- " + flag);
                    if(flag) {
                        count++;
                        urlList.add("http://10.0.10.16:8080/uploads/" + id + "/" + fileName + ".jpg");
                    }
                }
            }


            map.put("code", 0);
            map.put("count", count);
            map.put("url", urlList);
        } catch (Exception e) {
            logger.error("图片上传:", e);
        }
        return map;
    }
0 0
原创粉丝点击