AJAX上传Base64编码图片

SSM图片上传:https://blog.csdn.net/weixin_37595711/article/details/85109381

 1.html部分




    上传图片


  




  


 

2.controller

@RequestMapping(value = "/postBase64Img.action",method = RequestMethod.POST)
    public Object base64Img(@RequestParam("myPhoto") String base64Data, HttpServletRequest request) throws JsonProcessingException {
        HashMap hashMap=new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        try {
            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 imgName=UUID.randomUUID().toString();
            String tempFileName = imgName + suffix;
            LOGGER.debug("生成文件名为:"+tempFileName);

            //因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
            byte[] bs = Base64Utils.decodeFromString(data);
            try{
                File file=null;
                //使用apache提供的工具类操作流
                String url = request.getSession().getServletContext().getRealPath("/upload");
                FileUtils.writeByteArrayToFile(new File(url+"/" + tempFileName), bs);

                String pitureUrl=host+tempFileName;
                System.out.println(pitureUrl);
                hashMap.put("end","OK");
                hashMap.put("url",pitureUrl);
            }catch(Exception ee){

                throw new Exception("上传失败,写入文件失败,"+ee.getMessage());
            }

        }catch (Exception e){
            hashMap.put("end","upload err");
            e.printStackTrace();
        }
        return mapper.writeValueAsString(hashMap);
    }
}

3.工具类

package com.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

public class Base64Image {
    
    public static String GetImageStr(String imgFilePath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        byte[] data = null;

        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }

    public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}

结果

AJAX上传Base64编码图片_第1张图片

你可能感兴趣的:(文件服务器)