2015年12月27日 Java Coding 浏览(464) 收藏

Base64方式上传图片的Java源码

这里分享下本站通过Base64上传图片的java源码,支持struts、spring、servlet等,即是通用的上传功能。可将文件上传至指定目录。

上传代码方法一:

package com.everycoding.upload;

import java.util.Map;

import com.alibaba.fastjson.util.Base64;
import com.everycoding.upload.define.BaseState;
import com.everycoding.upload.define.FileType;
import com.everycoding.upload.define.State;

public final class Base64Uploader {
    public static State save(String content, Map<String, Object> conf) {
        byte[] data = decode(content);

        long maxSize = ((Long) conf.get("maxSize")).longValue();

        if (!validSize(data, maxSize)) {
            return new BaseState(false, 1);
        }

        String suffix = FileType.getSuffix("JPG");

        String savePath = PathFormat.parse((String) conf.get("savePath"), (String) conf.get("filename"));

        savePath = savePath + suffix;
        String physicalPath = (String) conf.get("rootPath") + savePath;

        State storageState = StorageManager.saveBinaryFile(data, physicalPath);

        if (storageState.isSuccess()) {
            storageState.putInfo("url", "http://images.everycoding.com/image"+PathFormat.format(savePath));
            storageState.putInfo("type", suffix);
            storageState.putInfo("original", "");
        }

        return storageState;
    }

    private static byte[] decode(String content) {
        return Base64.decodeFast(content);
    }

    private static boolean validSize(byte[] data, long length) {
        return data.length <= length;
    }
}

上传代码方法二:

@Override
    public void uploadAvatar(String fileBase64) {
        if (StringUtils.isEmpty(fileBase64)) {
            throw new NullPointerException("fileBase64 不能为null");
        } else {
            File tempImg = null;
            try {
                fileBase64 = fileBase64.replaceFirst("data:image/png;base64,", "");
                String classDir = this.getClass().getResource("/").getPath();
                String tempPath = classDir + "/" + System.currentTimeMillis() + ".png";
                byte[] byteimg = Base64.decodeFast(fileBase64.trim());
                for (int i = 0; i < byteimg.length; ++i) {
                    if (byteimg[i] < 0) {// 调整异常数据
                        byteimg[i] += 256;
                    }
                }
                FileOutputStream fos = new FileOutputStream(tempPath);
                fos.write(byteimg);
                fos.flush();
                fos.close();
                User user = SessionUtils.getUser();
                // 临时图片
                tempImg = new File(tempPath);
                String avatarUrl = StorePathUtil.genAvatarPicPath(user.getId(), user.getNickname(), user.getRegistTime());
                String rootPath = null;
                if (EnvUtil.isProdEnv()) {
                    rootPath = SysConfigUtil.get("avatarRootPath");
                } else {
                    rootPath = "D:/upload/avatar";
                }
                ImageUtil.compress( rootPath+avatarUrl, tempPath, 128, 128, 0.7f);
                String visitorUrl = "http://images.everycoding.com/avatar"+avatarUrl;
                this.userMapper.updateAvatar(user.getId(),visitorUrl);
                user.setAvatar(visitorUrl);
            } catch (Exception e) {
                logger.error("##上传图片失败", e);
                throw new UploadException("上传图片失败");
            } finally {
                if (tempImg != null) {
                    tempImg.delete();
                }
            }
        }
    }


赞一下 0 人赞了本文