springmvc:base64编码实现图片上传至服务器

问题:将前端返回的base64图片编码进行解码,并将图片保存至服务器 代码如下:

@ResponseBody
    @RequestMapping(value = "/insertCgComment", method = RequestMethod.POST)
    public int insertCgComment(String base64Data, HttpServletRequest request) throws IOException {
        String data = "";
        data = base64Data.split("base64,")[1];//获取base64的图片部分
        byte[] bs = Base64Utils.decodeFromString(data);//base64解码
        String filepath = request.getSession().getServletContext().getRealPath("/static");//获得根目录下的static文件路径
        System.out.println(filepath);
        String filename = filepath + File.separator + new SimpleDateFormat("yyyyMMddHHmmssSSS")
                .format(new Date())
                + (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000)
                + ".png";
        ; //用上传时间表示文件名防止冲突
        System.out.println(filename);
        //创建文件
        File imageFile = new File(filename);
        if(!imageFile.exists()){
            imageFile.createNewFile();
        }
        //将二进制写入文件
        OutputStream imageStream = new FileOutputStream(filename);
        imageStream.write(bs);
        imageStream.flush();
        imageStream.close();
        return 1;
    }

可能出现的问题:点击跳转至解决方法

3.图片上传至服务器后无法访问 在springmvc.xml中插入

<!-- Spring MVC不处理静态资源 -->
    <mvc:default-servlet-handler />
经验分享 程序员 微信小程序 职场和发展