七牛云的使用

当七牛云存储区域地域简称不对就会抛以下异常

{ResponseInfo:com.qiniu.http.Response@46238e3f,status:400, reqId:5cYAAAADmTAShB8W, xlog:X-Log, xvia:,

adress:up-z1.qiniu.com/222.222.95.22:80, duration:0.000000 s,

error:incorrect region, please use up-z0.qiniup.com}


{"error":"incorrect region, please use up-z0.qiniup.com"}

提醒把z1改为  Z0即可

 

代码如下:

package com.itheima.test;

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;

import org.junit.Test;

public class QiNiuTest {
//使用七牛云提供的SDK实现将本地图片上传到七牛云服务器
@Test
public void test1() {
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Zone.zone0());//此处空间如果不对就报错
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证,然后准备上传
String accessKey = "o0chJ24lILmSRpgp4CmbNrA_2RVdz-unUmR-ZhE7";//七牛云个人中心,密钥管理中的AK
String secretKey = "Fw5UJRZUKJnNkaYqhyKiZe5VDtHq72w8GYJtPozw";//七牛云个人中心,密钥管理中的SK
String bucket = "itcasthealth-space-14";//空间名称
//如果是Windows情况下,格式是 D:\\qiniu\\test.png
String localFilePath = "D:\\图片\\a.png";//本地网盘位置和图片具体名称
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = null;//如果在此处null改为“abc。jpg”上传图片就是这个名字
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(localFilePath, key, upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
}
}

 

外链:   http://qcycggk07.bkt.clouddn.com/b.png

 

七牛云的删除操作和上传差不多

public void test2() {

//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Zone.zone0());//此处空间如果不对就报错
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证,然后准备上传
String accessKey = "o0chJ24lILmSRpgp4CmbNrA_2RVdz-unUmR-ZhE7";//七牛云个人中心,密钥管理中的AK
String secretKey = "Fw5UJRZUKJnNkaYqhyKiZe5VDtHq72w8GYJtPozw";//七牛云个人中心,密钥管理中的SK
String bucket = "itcasthealth-space-14";//空间名称
String key = "Fu3Ic6TV6wIbJt793yaGeBmCkzTX";//删除里面的名字必须和七牛云上传名字一致,否则无法删除,抛异常

Auth auth = Auth.create(accessKey, secretKey);
BucketManager bucketManager = new BucketManager(auth, cfg);

try {
bucketManager.delete(bucket, key);
} catch (QiniuException ex) {
//如果遇到异常,说明删除失败
System.err.println(ex.code());
System.err.println(ex.response.toString());
}
posted @ 2020-07-08 00:10  Monica_维维  阅读(1085)  评论(0编辑  收藏  举报