七牛云上传文件

时间:2021-11-05 04:48:37
public class QiNiuUtils {

Configuration cfg = new Configuration(Zone.zone1());
UploadManager uploadManager = new UploadManager(cfg);
String ACCESS_KEY = Constants.JTS_QI_NIU_ACCESS_KEY;
String SECRET_KEY = Constants.JTS_QI_NIU_SECRET_KEY;
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
//简单上传,使用默认策略,只需要设置上传的空间名就可以了
public String getUpToken(){
return auth.uploadToken(Constants.JTS_QI_NIU_BUCKET);
}

//普通上传
public String upload(File file,String key) throws IOException {
String url = "";
try {
//调用put方法上传
Response res = uploadManager.put(file, key, getUpToken());
//打印返回的信息
JSONObject jsonObject = JSONObject.fromObject(res.bodyString());
ApiLogger.info("上传成功:文件名称"+jsonObject.getString("key"));
url = jsonObject.getString("key");
} catch (QiniuException e) {
Response r = e.response;
// 请求失败时打印的异常的信息
System.out.println(r.toString());
try {
//响应的文本信息
System.out.println(r.bodyString());
} catch (QiniuException e1) {
//ignore
}
}
return url;
}

public static void main(String[] args) throws Exception {
new QiNiuUtils().upload(new File("d:\\woshuhanzikeyima.jpg"),"自定义名称.jpg");

}