springboot上传文件到七牛云

一、环境准备

  • 注册七牛云账号
  • 七牛云中建立一个存储桶

二、导入maven依赖



    com.qiniu
    qiniu-java-sdk
    [7.2.0, 7.2.99]



    com.alibaba
    fastjson
    1.2.28

三、配置文件

本次采用yml形式,也可以采用properties形式

qiniu:
  accessKey: CX-xxxx-53jguexjbMfb3cH
  secretKey: D40BcITIAx-xxx-Ia-fT-31-cc-j6
  bucket: xxx-images
  path: http://xxx.bkt.clouddn.com

四、书写工具类

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.FileInputStream;

@Component
public class QiniuUtil {

    @Value("${qiniu.accessKey}")
    private String accessKey;

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

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

    @Value("${qiniu.path}")
    private String path;

    /**
     * 将图片上传到七牛云
     *
     * @param file
     * @param key  保存在空间中的名字,如果为空会使用文件的hash值为文件名
     * @return
     */
    public String uploadImg(FileInputStream file, String key) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone1());
		//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
		//...生成上传凭证,然后准备上传
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        try {
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(file, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
                String return_path = path + "/" + putRet.key;
                return return_path;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "";
    }
}

你可能感兴趣的:(web)