官方文档:https://developer.qiniu.com/kodo/1239/java
public void upload(){
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.huanan());
UploadManager uploadManager = new UploadManager(cfg);
//生成上传凭证,然后准备上传
String accessKey = "xxx";
String secretKey = "xxx";
//存储空间
String bucket = "xxx";
//如果是Windows情况下,格式是 D:\\qiniu\\test.png
String localFilePath = "F:\\2021.jpg";
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = null;
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
}
}
}
public void download() {
String fileName = "xxx"; //不需要文件后缀
String domainOfBucket = "http://xxx.com";
try {
String encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
String accessKey = "xxx";
String secretKey = "xxx";
Auth auth = Auth.create(accessKey, secretKey);
long expireInSeconds = 3600;//1小时,可以自定义链接过期时间
String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
System.out.println(finalUrl);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。