采用base64编码上传图片

来源:互联网 发布:如何引出大数据 编辑:程序博客网 时间:2024/05/18 02:54

需求:前端将图片转化为base64编码数据,传到后台,再将图片上传到服务器特定位置。

public class UploadTool {    /**     * 上传图片     *      * @param base64     * 图片编码后的字符串     * @return 上传成功后的文件名     */    public static String upload(String base64) {        if ((base64 != null) && !(base64.equals(""))) {            // upload是图片上传路径            String dir = ServletActionContext.getServletContext().getRealPath("/upload");            File fileLocation = new File(dir);            // 判断上传路径是否存在,如果不存在就创建            if (!fileLocation.exists()) {                boolean isCreated = fileLocation.mkdir();                if (!isCreated) {                    // 目标上传目录创建失败,可做其他处理,例如抛出自定义异常等,一般应该不会出现这种情况。                    return null;                }            }            if (base64.indexOf("jpeg") != -1) {                // base64字串中有jpeg字串,这是一个4个字的,而我这里是把base64字串的指定位置的字串来作为上传                // 文件类型的判断依据,所以在大部分都是三个字的文件类型下就得把jpeg改成jpg了                base64 = base64.replaceFirst("jpeg", "jpg");            }            // 生成一个唯一的文件名            Random random = new Random();            int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数            String thisdate = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()).replace(":", "_")                    .replace(" ", "_");            String newphotoname = "yuefu8_" + rannum + "_" + thisdate + "." + base64.substring(11, 14);            FileOutputStream out;            String iconBase64 = base64.substring(22);            try {                byte[] buffer = new BASE64Decoder().decodeBuffer(iconBase64);                out = new FileOutputStream(dir + "/" + newphotoname);                out.write(buffer);                out.close();                return newphotoname;            } catch (FileNotFoundException e) {                e.printStackTrace();                return null;            } catch (IOException e) {                e.printStackTrace();                return null;            }        }else{            return null;        }    }}
0 0