Java 七牛云文件上传(本地)

引入pom.xml


        
            com.qiniu
            qiniu-java-sdk
            7.2.0
        

配置文件QiNiuContant.java

/**
 * 七牛的配置文件
 * */
public class QiNiuContant {
    //每个七牛云仓库对应两对密钥
    public final static String AccessKey = "AccessKey ";
    public final static String SecretKey = "SecretKey ";

    public final static String __AccessKey__ = "AccessKey ";
    public final static String __SecretKey__  = "SecretKey ";

    public final static String bucketName = "bucketName";
}

主要QiNiuUtil.java

import com.education.ak1.contant.QiNiuContant;
import com.google.gson.Gson;
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;

public class QiNiuUtil {

    public static String getUpToken(){
        Auth auth = Auth.create(QiNiuContant.AccessKey, QiNiuContant.SecretKey);
        String uptoken = auth.uploadToken("ak1ak1");
        return uptoken;
    }

    public static void  upload(String key, String localPath) {
        Configuration cfg = new Configuration(Zone.zone2());//设置华南的服务器
        UploadManager uploadManager = new UploadManager(cfg);

        String upToken = getUpToken();
        try {
            Response response = uploadManager.put(localPath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        }catch (QiniuException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception{
        upload("1234","E:\\VID_20190406_145318.mp4");
    }

}

特别注意:不同的区域选区的Zone.zone不同

你可能感兴趣的:(java,七牛云,上传文件)