七牛云图片上传-JAVA

注册

注册一个七牛账号,注册链接:点击注册 ,注册成功之后最好实名认证一下,每个月的流量以及空间的容量会增加很多。

新建空间

新建一个空间,记下空间名称(bucketName)。在账号里找到密钥:AK,SK。后面开发中会用到这些。

引入依赖

使用maven管理,自动下载对应jar包


    com.qiniu
    pili-sdk-java
    1.5.4


    com.qiniu
    qiniu-java-sdk
    7.1.3

编编编编编编码

初始化七牛配置文件

在配置文件中加入七牛配置

#--------七牛配置
qiniu.access.key=你的AK
qiniu.secret.key=你的SK
qiniu.bucket.name=你的bucketName
qiniu.bucket.host.name=你的外链默认域名
#--------七牛配置

文件上传接口

public interface UploadUtil {
String uploadFile(MultipartFile multipartFile) throws UploadException;

    String uploadFile(String filePath, MultipartFile multipartFile) throws UploadException;

    String uploadFile(MultipartFile multipartFile, String fileName) throws UploadException;

    String uploadFile(MultipartFile multipartFile, String fileName, String filePath) throws UploadException;

    String uploadFile(File file) throws UploadException;

    String uploadFile(String filePath, File file) throws UploadException;

    String uploadFile(File file, String fileName) throws UploadException;

    String uploadFile(File file, String fileName, String filePath) throws UploadException;

    String uploadFile(byte[] data) throws UploadException;

    String uploadFile(String filePath, byte[] data) throws UploadException;

    String uploadFile(byte[] data, String fileName) throws UploadException;

    String uploadFile(byte[] data, String fileName, String filePath) throws UploadException;
}

文件上传接口实现

public class QiniuUtil implements UploadUtil {

    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    private String bucketHostName;

    private String bucketName;

    private Auth auth;

    private UploadManager uploadManager = new UploadManager();

    /**
     * 构造函数
     *
     * @param bucketHostName 七牛域名
     * @param bucketName     七牛空间名
     * @param auth           七牛授权
     */
    public QiniuUtil(String bucketHostName, String bucketName, Auth auth) {
        this.bucketHostName = bucketHostName;
        this.bucketName = bucketName;
        this.auth = auth;
    }

    public String generate(){
        return this.generateToken();
    }


    /**
     * 根据spring mvc 文件接口上传
     *
     * @param multipartFile spring mvc 文件接口
     * @return 文件路径
     * @throws IOException
     */
    @Override
    public String uploadFile(MultipartFile multipartFile) throws UploadException {
        byte[] bytes = getBytesWithMultipartFile(multipartFile);
        return this.uploadFile(bytes);
    }

    /**
     * 根据spring mvc 文件接口上传
     *
     * @param filePath      文件前缀,例如:/test或者/test/
     * @param multipartFile spring mvc 文件接口
     * @return 文件路径
     * @throws IOException
     */
    @Override
    public String uploadFile(String filePath, MultipartFile multipartFile) throws UploadException {
        byte[] bytes = getBytesWithMultipartFile(multipartFile);
        return this.uploadFile(filePath, bytes);
    }

    /**
     * 根据spring mvc 文件接口上传
     *
     * @param multipartFile spring mvc 文件接口
     * @param fileName      文件名
     * @return 文件路径
     * @throws IOException
     */
    @Override
    public String uploadFile(MultipartFile multipartFile, String fileName) throws UploadException {
        byte[] bytes = getBytesWithMultipartFile(multipartFile);
        return this.uploadFile(bytes, fileName);
    }


    /**
     * 根据spring mvc 文件接口上传
     *
     * @param multipartFile spring mvc 文件接口
     * @param fileName      文件名
     * @param filePath      文件前缀,例如:/test或者/test/
     * @return 文件路径
     * @throws IOException
     */
    @Override
    public String uploadFile(MultipartFile multipartFile, String fileName, String filePath) throws UploadException {
        byte[] bytes = getBytesWithMultipartFile(multipartFile);
        return this.uploadFile(bytes, fileName, filePath);
    }


    /**
     * 根据spring mvc 文件接口上传
     *
     * @param file 文件
     * @return 文件路径
     * @throws UploadException
     */
    @Override
    public String uploadFile(File file) throws UploadException {
        return this.uploadFile(file, null, null);
    }

    /**
     * 根据spring mvc 文件接口上传
     *
     * @param file     文件
     * @param filePath 文件前缀,例如:/test或者/test/
     * @return 文件路径
     * @throws UploadException
     */
    @Override
    public String uploadFile(String filePath, File file) throws UploadException {
        return this.uploadFile(file, null, filePath);
    }

    /**
     * 根据spring mvc 文件接口上传
     *
     * @param file     文件
     * @param fileName 文件名
     * @return 文件路径
     * @throws UploadException
     */
    @Override
    public String uploadFile(File file, String fileName) throws UploadException {
        return this.uploadFile(file, fileName, null);
    }

    /**
     * 根据spring mvc 文件接口上传
     *
     * @param file     文件
     * @param fileName 文件名
     * @param filePath 文件前缀,例如:/test或者/test/
     * @return 文件路径
     * @throws UploadException
     */
    @Override
    public String uploadFile(File file, String fileName, String filePath) throws UploadException {
        String key = preHandle(fileName, filePath);
        Response response = null;
        try {
            response = this.uploadManager.put(file, key, this.generateToken());
        } catch (QiniuException e) {
            LOGGER.warn("QiniuException:", e);
            throw new UploadException(e.getMessage());
        }
        return this.getUrlPath(response);
    }

    /**
     * 根据spring mvc 文件接口上传
     *
     * @param data 文件
     * @return 文件路径
     * @throws UploadException
     */
    @Override
    public String uploadFile(byte[] data) throws UploadException {
        return this.uploadFile(data, null, null);
    }

    /**
     * 根据spring mvc 文件接口上传
     *
     * @param data     文件
     * @param filePath 文件前缀,例如:/test或者/test/
     * @return 文件路径
     * @throws UploadException
     */
    @Override
    public String uploadFile(String filePath, byte[] data) throws UploadException {
        return this.uploadFile(data, null, filePath);
    }

    /**
     * 根据spring mvc 文件接口上传
     *
     * @param data     文件
     * @param fileName 文件名
     * @return 文件路径
     * @throws UploadException
     */
    @Override
    public String uploadFile(byte[] data, String fileName) throws UploadException {
        return this.uploadFile(data, fileName, null);
    }

    /**
     * 根据spring mvc 文件接口上传
     *
     * @param data     文件
     * @param fileName 文件名
     * @param filePath 文件前缀,例如:/test或者/test/
     * @return 文件路径
     * @throws UploadException
     */
    @Override
    public String uploadFile(byte[] data, String fileName, String filePath) throws UploadException {
        String key = preHandle(fileName, filePath);
        Response response;
        try {
            response = this.uploadManager.put(data, key, generateToken());
        } catch (QiniuException e) {
            LOGGER.error("QiniuException:", e);
            throw new UploadException(e.getMessage());
        }
        return this.getUrlPath(response);
    }

    private byte[] getBytesWithMultipartFile(MultipartFile multipartFile) {
        try {
            return multipartFile.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private String preHandle(String fileName, String filePath) throws UploadException {
        if (StringUtils.isNotBlank(fileName) && !fileName.contains(".")) {
            throw new UploadException("文件名必须包含尾缀");
        }
        if (StringUtils.isNotBlank(filePath) && !filePath.startsWith("/")) {
            throw new UploadException("前缀必须以'/'开头");
        }
        String name = StringUtils.isBlank(fileName) ? RandomStringUtils.randomAlphanumeric(32) : fileName;
        if (StringUtils.isBlank(filePath)) {
            return name;
        }
        String prefix = filePath.replaceFirst("/", "");
        return (prefix.endsWith("/") ? prefix : prefix.concat("/")).concat(name);
    }

    private String generateToken() {
        return this.auth.uploadToken(bucketName);
    }


    private String getUrlPath(Response response) throws UploadException {
        if (!response.isOK()) {
            throw new UploadException("文件上传失败");
        }
        DefaultPutRet defaultPutRet;
        try {
            defaultPutRet = response.jsonToObject(DefaultPutRet.class);
        } catch (QiniuException e) {
            LOGGER.warn("QiniuException", e);
            throw new UploadException(e.getMessage());
        }
        String key = defaultPutRet.key;
        if (key.startsWith(bucketHostName)) {
            return key;
        }
        return bucketHostName + (key.startsWith("/") ? key : "/" + key);
    }

}

接口实例化

public class UploadFactory {

    public static UploadUtil createUpload(String accessKey, String secretKeySpec, String bucketHostName, String bucketName) {
        Auth auth = Auth.create(accessKey, secretKeySpec);
        return new QiniuUtil(bucketHostName, bucketName, auth);
    }

}

传上你的小黄图

@Service
public class UploadService extends BaseService {

    //引入第一步的七牛配置
    @Value("${qiniu.access.key}")
    private String accesskey;

    @Value("${qiniu.secret.key}")
    private String secretKey;

    @Value("${qiniu.bucket.name}")
    private String bucketName;

    @Value("${qiniu.bucket.host.name}")
    private String bucketHostName;

    public String uploadImage(MultipartFile image) throws UploadException {
        UploadUtil uploadUtil = UploadFactory.createUpload(this.accesskey, this.secretKey,
                this.bucketHostName, this.bucketName);
        return uploadUtil.uploadFile("/filePath/", image);
    }
}

简不简单?惊不惊喜?意不意外?开不开心?

你可能感兴趣的:(七牛云图片上传-JAVA)