对象存储 UFile:对象存储(UFile)是为互联网应用提供非结构化文件云存储的服务;相对于传统硬盘存储,UFile云存储具有存储无上限、支持高并发访问、成本更低等优势;解决业务架构的文件存储问题,有效降低海量文件的存储成本,支持热点数据的高并发访问,提升终端用户访问体验。实名认证用户均可享受20GB免费云存储空间和20GB/月免费下载流量。
https://www.ucloud.cn/site/product/ufile.html
https://github.com/ucloud/ufile-sdk-java
https://docs.ucloud.cn/api/ufile-api/
https://github.com/ucloud/ufile-sdk-java/tree/master/ufile-sample-java
cn.ucloud.ufile
ufile-client-java
2.4.2
dependencies {
/*
* your other dependencies
*/
implementation 'cn.ucloud.ufile:ufile-client-java:2.4.2'
}
基本说明:
所有Ufile所有API均包含同步执行(execute)和异步执行(executeAsync)两种执行方式。
同步执行会返回指定的业务结果类,若执行出错则会抛出UfileException为父类的异常;
异步执行需要传入UfileCallback的回调接口,执行成功时会回调onResponse,泛型为回调结果(即:同步执行的返回类型),值得注意的是,若Ufile Server业务错误,也会回调onResponse,请注意结果类中的信息,若出现异常,则回调onError。
如果是上传下载等耗时API,建议使用异步执行(executeAsync),并可以重写UfileCallback中的onProgress回调来进行进度监听
必须在使用UfileClient之前调用,即:必须是UfileClient第一个调用的方法才有效。否则使用默认UfileClient.Config
UfileClient.configure(new UfileClient.Config(
new HttpClient.Config(int maxIdleConnections, long keepAliveDuration, TimeUnit keepAliveTimeUnit)
.setTimeout(连接超时ms,读取超时ms,写入超时ms)
.setExecutorService(线程池)
.addInterceptor(okhttp3拦截器)
.addNetInterceptor(okhttp3网络拦截器)));
// Bucket相关API的授权器
BucketAuthorization BUCKET_AUTHORIZER = new UfileBucketLocalAuthorization(
"Your PublicKey", "Your PrivateKey");
UfileClient.bucket(BUCKET_AUTHORIZER)
.APIs // Bucket相关操作API
.execute() or executeAsync(UfileCallback)
try {
BucketResponse res = UfileClient.bucket(BUCKET_AUTHORIZER)
.createBucket(bucketName, region, bucketType)
.execute();
} catch (UfileClientException e) {
e.printStackTrace();
} catch (UfileServerException e) {
e.printStackTrace();
}
UfileClient.bucket(BUCKET_AUTHORIZER)
.createBucket(bucketName, region, bucketType)
.executeAsync(new UfileCallback() {
@Override
public void onResponse(BucketResponse response) {
}
@Override
public void onError(Request request, ApiError error, UfileErrorBean response) {
}
});
关于ObjectConfig的region参数,是指您的bucket所创建在的地区编码,请参考UCloud 地区列表
// 对象相关API的授权器
ObjectAuthorization OBJECT_AUTHORIZER = new UfileObjectLocalAuthorization(
"Your PublicKey", "Your PrivateKey");
/**
* 您也可以创建远程对象相关API的授权器,远程授权器将签名私钥放于签名服务器上,更为安全
* 远程签名服务端示例代码在 (https://github.com/ucloud/ufile-sdk-auth-server)
* 您也可以自行继承ObjectRemoteAuthorization来重写远程签名逻辑
*/
ObjectAuthorization OBJECT_AUTHORIZER = new UfileObjectRemoteAuthorization(
您的公钥,
new ObjectRemoteAuthorization.ApiConfig(
"http://your_domain/applyAuth",
"http://your_domain/applyPrivateUrlAuth"
));
// 对象操作需要ObjectConfig来配置您的地区和域名后缀
ObjectConfig config = new ObjectConfig("your bucket region", "ufileos.com");
/**
* 您也可以使用已登记的自定义域名
* 注意'http://www.your_domain.com'指向的是某个特定的bucket+region+域名后缀,
* eg:http://www.your_domain.com -> www.your_bucket.bucket_region.ufileos.com
*/
ObjectConfig config = new ObjectConfig("http://www.your_domain.com");
/**
* ObjectConfig同时支持从本地文件来导入
* 配置文件内容必须是含有以下参数的json字符串:
* {"Region":"","ProxySuffix":""}
* 或
* {"CustomDomain":""}
*/
try {
ObjectConfig.loadProfile(new File("your config profile path"));
} catch (UfileFileException e) {
e.printStackTrace();
}
UfileClient.object(OBJECT_AUTHORIZER, config)
.APIs // 对象存储相关API
.execute() or executeAsync(UfileCallback)
File file = new File("your file path");
try {
PutObjectResultBean response = UfileClient.object(Constants.OBJECT_AUTHORIZER, config)
.putObject(file, "mimeType")
.nameAs("save as keyName")
.toBucket("upload to which bucket")
/**
* 是否上传校验MD5, Default = true
*/
// .withVerifyMd5(false)
/**
* 指定progress callback的间隔, Default = 每秒回调
*/
// .withProgressConfig(ProgressConfig.callbackWithPercent(10))
/**
* 配置进度监听
*/
.setOnProgressListener(new OnProgressListener() {
@Override
public void onProgress(long bytesWritten, long contentLength) {
}
})
.execute();
} catch (UfileClientException e) {
e.printStackTrace();
} catch (UfileServerException e) {
e.printStackTrace();
}
File file = new File("your file path");
UfileClient.object(OBJECT_AUTHORIZER, config)
.putObject(file, "mimeType")
.nameAs("save as keyName")
.toBucket("upload to which bucket")
/**
* 是否上传校验MD5, Default = true
*/
// .withVerifyMd5(false)
/**
*指定progress callback的间隔, Default = 每秒回调
*/
// .withProgressConfig(ProgressConfig.callbackWithPercent(10))
.executeAsync(new UfileCallback() {
@Override
public void onProgress(long bytesWritten, long contentLength) {
}
@Override
public void onResponse(PutObjectResultBean response) {
}
@Override
public void onError(Request request, ApiError error, UfileErrorBean response) {
}
});
ufile.bucketName=your bucketName
ufile.UCloudPublicKey=your UCloudPublicKey
ufile.UCloudPrivateKey=your UCloudPrivateKey
ufile.ProxySuffix=.cn-bj.ufileos.com
ufile.DownloadProxySuffix=.ufile.ucloud.com.cn
说明:
bucketName:上传域名的前缀 例如:weiyiyuming
UCloudPublicKey 请改成用户的公钥
UCloudPrivateKey 请改成用户的私钥
ProxySuffix 指定上传域名的后缀,可以填写源站的后缀(例如北京地域 .cn-bj.ufileos.com)或内网域名的后缀
DownloadProxySuffix 指定下载域名的后缀,可以填写源站(例如北京地域 .cn-bj.ufileos.com)或加速域名的后缀 (.ufile.ucloud.com.cn)
资源工具类:ResourceBundle这个类是用于专门读取properties文件的
import java.text.MessageFormat;
import java.util.ResourceBundle;
/**
* 资源文件工具类
*/
public class ResourceUtil {
private ResourceBundle resourceBundle;
private ResourceUtil(String resource) {
resourceBundle = ResourceBundle.getBundle(resource);
}
public static ResourceUtil getResource(String resource) {
return new ResourceUtil(resource);
}
public String getValue(String key) {
return resourceBundle.getString(key);
}
public String getValue(String key, Object... args) {
String temp = resourceBundle.getString(key);
return MessageFormat.format(temp, args);
}
}
UFile工具类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import org.apache.http.Header;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.ucloud.ufile.UFileClient;
import cn.ucloud.ufile.UFileConfig;
import cn.ucloud.ufile.UFileRequest;
import cn.ucloud.ufile.UFileResponse;
import cn.ucloud.ufile.sender.DeleteSender;
import cn.ucloud.ufile.sender.GetSender;
import cn.ucloud.ufile.sender.PutSender;
/**
* ufile操作工具
* Created by win 10 on 2018/4/11.
*/
public class UfileUtil {
private static final Logger logger = LoggerFactory.getLogger(UfileUtil.class);
private static final ResourceUtil resourceUtil=ResourceUtil.getResource("ufile");
// 文件分类地址,可以自定义
private static final String bucketName = resourceUtil.getValue("ufile.bucketName");
private static final String UCloudPublicKey=resourceUtil.getValue("ufile.UCloudPublicKey");
private static final String UCloudPrivateKey=resourceUtil.getValue("ufile.UCloudPrivateKey");
private static final String ProxySuffix=resourceUtil.getValue("ufile.ProxySuffix");
private static final String DownloadProxySuffix=resourceUtil.getValue("ufile.DownloadProxySuffix");
//图片大小
public static Integer ImageSize=Integer.valueOf(resourceUtil.getValue("ufile.imageSize"));
//图片路径前缀
public static final String PathProxySuffix=resourceUtil.getValue("ufile.pathProxySuffix");
static {
UFileConfig.getInstance().setUcloudPublicKey(UCloudPublicKey);
UFileConfig.getInstance().setUcloudPrivateKey(UCloudPrivateKey);
UFileConfig.getInstance().setProxySuffix(ProxySuffix);
UFileConfig.getInstance().setDownloadProxySuffix(DownloadProxySuffix);
}
/**
* 上传文件 根据官方文档,本方法中只有relativeUlr是必须的,其他三个参数都是非必须
* @param relativeUrl 文件上传至ufile的地址 如:/images/xxx.png
* @param contentType 自定义文件类型
* @param inputStream
* @param contentLength
* @throws IOException
*/
public static void uploadFile(String relativeUrl, String
contentType, InputStream inputStream, long contentLength) throws IOException {
UFileRequest request = new UFileRequest();
request.setBucketName(bucketName);
System.out.println("文件url:"+relativeUrl);
request.setKey(relativeUrl);
request.setContentType(contentType);
request.setInputStream(inputStream);
request.setContentLength(contentLength);
UFileClient ufileClient = new UFileClient();
System.out.println("===================================");
String ucloudPrivateKey2 = UFileConfig.getInstance().getUcloudPrivateKey();
System.out.println("ProxySuffix:"+ UFileConfig.getInstance().getProxySuffix());
System.out.println("DownloadProxySuffix:"+ UFileConfig.getInstance().getDownloadProxySuffix());
System.out.println("私匙:"+ucloudPrivateKey2);
System.out.println("公匙:"+UFileConfig.getInstance().getUcloudPublicKey());
System.out.println("===================================");
putFile(ufileClient, request);
ufileClient.shutdown();
inputStream.close();
}
/**
* 下载文件
* @param relativeUrl
* @param contentType
* @param outputStream
*/
public void downloadFile(String relativeUrl, String contentType, OutputStream
outputStream) {
UFileRequest request = new UFileRequest();
request.setBucketName(bucketName);
request.setKey(relativeUrl);
UFileClient ufileClient = null;
try {
ufileClient = new UFileClient();
getFile(ufileClient, request, outputStream);
}
catch (Exception e) {
logger.error("读取回执发生异常,relativeUrl={},{}", relativeUrl, e);
}
finally {
ufileClient.shutdown();
try {
outputStream.close();
}
catch (IOException e) {
logger.error("", e);
}
}
}
public static void deleteFile(String relativeUrl) {
UFileRequest request = new UFileRequest();
request.setBucketName(bucketName);
request.setKey(relativeUrl);
UFileClient ufileClient = null;
try {
ufileClient = new UFileClient();
deleteFile(ufileClient, request);
}
finally {
ufileClient.shutdown();
}
}
private static void putFile(UFileClient ufileClient, UFileRequest request) throws
IOException {
PutSender sender = new PutSender();
sender.makeAuth(ufileClient, request);
UFileResponse response = sender.send(ufileClient, request);
if (response != null) {
InputStream inputStream = response.getContent();
if (inputStream != null) {
BufferedReader reader = new BufferedReader(new
InputStreamReader(inputStream));
String s = "";
while ((s = reader.readLine()) != null) {
logger.info(s);
}
inputStream.close();
}
}
}
private static void getFile(UFileClient ufileClient, UFileRequest request,
OutputStream outputStream) {
GetSender sender = new GetSender();
sender.makeAuth(ufileClient, request);
UFileResponse response = sender.send(ufileClient, request);
if (response != null) {
if (response.getStatusLine().getStatusCode() != 200 && response.getContent()
!= null) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(response.getContent()));
String input;
while ((input = br.readLine()) != null) {
logger.info(input);
}
}
catch (IOException e) {
logger.error("", e);
}
finally {
if (response.getContent() != null) {
try {
response.getContent().close();
}
catch (IOException e) {
logger.error("", e);
}
}
}
}
else {
InputStream inputStream = null;
try {
inputStream = response.getContent();
int bufSize = 1024 * 4;
byte[] buffer = new byte[bufSize];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, bytesRead);
}
}
catch (IOException e) {
logger.error("", e);
}
finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
logger.error("", e);
}
}
if (outputStream != null) {
try {
outputStream.close();
}
catch (IOException e) {
logger.error("", e);
}
}
}
}
}
}
private static void deleteFile(UFileClient ufileClient, UFileRequest request) {
DeleteSender sender = new DeleteSender();
sender.makeAuth(ufileClient, request);
UFileResponse response = sender.send(ufileClient, request);
if (response != null) {
System.out.println("status line: " + response.getStatusLine());
Header[] headers = response.getHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println("header " + headers[i].getName() + " : " +
headers[i].getValue());
}
System.out.println("body length: " + response.getContentLength());
if (response.getContent() != null) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(response.getContent()));
String input;
while ((input = br.readLine()) != null) {
System.out.println(input);
}
}
catch (IOException e) {
logger.error("", e);
}
finally {
if (br != null) {
try {
br.close();
}
catch (IOException e) {
logger.error("", e);
}
}
}
}
}
}
}
application.properties
ucloud.ufile.public-key=TOKEN_f465454a-f3ab-4c9b-91a5-c7babf59cc38
ucloud.ufile.private-key=18977163-f21e-4deb-a2e3-9bfa0b888ba5
ucloud.ufile.bucket-name=mawen
ucloud.ufile.region=cn-bj
ucloud.ufile.suffix=ufileos.com
ucloud.ufile.expires=315360000
源代码
import cn.ucloud.ufile.UfileClient;
import cn.ucloud.ufile.api.object.ObjectConfig;
import cn.ucloud.ufile.auth.ObjectAuthorization;
import cn.ucloud.ufile.auth.UfileObjectLocalAuthorization;
import cn.ucloud.ufile.bean.PutObjectResultBean;
import cn.ucloud.ufile.exception.UfileClientException;
import cn.ucloud.ufile.exception.UfileServerException;
import life.majiang.community.exception.CustomizeErrorCode;
import life.majiang.community.exception.CustomizeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.util.UUID;
/**
* Created by codedrinker on 2019/6/28.
*/
@Service
@Slf4j
public class UCloudProvider {
@Value("${ucloud.ufile.public-key}")
private String publicKey;
@Value("${ucloud.ufile.private-key}")
private String privateKey;
@Value("${ucloud.ufile.bucket-name}")
private String bucketName;
@Value("${ucloud.ufile.region}")
private String region;
@Value("${ucloud.ufile.suffix}")
private String suffix;
@Value("${ucloud.ufile.expires}")
private Integer expires;
public String upload(InputStream fileStream, String mimeType, String fileName) {
String generatedFileName;
String[] filePaths = fileName.split("\\.");
if (filePaths.length > 1) {
generatedFileName = UUID.randomUUID().toString() + "." + filePaths[filePaths.length - 1];
} else {
throw new CustomizeException(CustomizeErrorCode.FILE_UPLOAD_FAIL);
}
try {
ObjectAuthorization objectAuthorization = new UfileObjectLocalAuthorization(publicKey, privateKey);
ObjectConfig config = new ObjectConfig(region, suffix);
PutObjectResultBean response = UfileClient.object(objectAuthorization, config)
.putObject(fileStream, mimeType)
.nameAs(generatedFileName)
.toBucket(bucketName)
.setOnProgressListener((bytesWritten, contentLength) -> {
})
.execute();
if (response != null && response.getRetCode() == 0) {
String url = UfileClient.object(objectAuthorization, config)
.getDownloadUrlFromPrivateBucket(generatedFileName, bucketName, expires)
.createUrl();
return url;
} else {
log.error("upload error,{}", response);
throw new CustomizeException(CustomizeErrorCode.FILE_UPLOAD_FAIL);
}
} catch (UfileClientException e) {
log.error("upload error,{}", fileName, e);
throw new CustomizeException(CustomizeErrorCode.FILE_UPLOAD_FAIL);
} catch (UfileServerException e) {
log.error("upload error,{}", fileName, e);
throw new CustomizeException(CustomizeErrorCode.FILE_UPLOAD_FAIL);
}
}
}
package com.zstu.metrocity.provider;
import cn.ucloud.ufile.UfileClient;
import cn.ucloud.ufile.api.ApiError;
import cn.ucloud.ufile.api.object.ObjectConfig;
import cn.ucloud.ufile.api.object.policy.PolicyParam;
import cn.ucloud.ufile.api.object.policy.PutPolicy;
import cn.ucloud.ufile.api.object.policy.PutPolicyForCallback;
import cn.ucloud.ufile.auth.*;
import cn.ucloud.ufile.bean.PutObjectResultBean;
import cn.ucloud.ufile.bean.UfileErrorBean;
import cn.ucloud.ufile.exception.UfileClientException;
import cn.ucloud.ufile.exception.UfileServerException;
import cn.ucloud.ufile.http.HttpClient;
import cn.ucloud.ufile.http.OnProgressListener;
import cn.ucloud.ufile.http.UfileCallback;
import cn.ucloud.ufile.util.StorageType;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.InputStream;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @Author ShenTuZhiGang
* @Version 1.0.0
* @Date 2020-04-16 20:55
*/
@Service
@Slf4j
public class UCloudProvider {
@Value("${ucloud.ufile.public-key}")
private String publicKey;
@Value("${ucloud.ufile.private-key}")
private String privateKey;
@Value("${ucloud.ufile.bucket-name}")
private String bucketName;
@Value("${ucloud.ufile.region}")
private String region;
@Value("${ucloud.ufile.proxy-suffix}")
private String proxySuffix;
@Value("${ucloud.ufile.expires}")
private Integer expires;
@Value("${ucloud.ufile.log.tag}")
private String tag;
static {
/**
* 配置UfileClient,必须在使用UfileClient之前调用
*/
UfileClient.configure(new UfileClient.Config(
new HttpClient.Config(10, 5, TimeUnit.MINUTES)
.setTimeout(10 * 1000, 30 * 1000, 30 * 1000)
.setExecutorService(Executors.newSingleThreadExecutor())));
}
@Autowired
private BucketAuthorization bucketAuthorization;
@Autowired
private UfileObjectLocalAuthorization objectAuthorization;
@Autowired
private UfileObjectRemoteAuthorization objectRemoteAuthorization;
@Autowired
private ObjectConfig config;
public String putFile(File file, String mimeType, String nameAs){
return putFile(file, mimeType, nameAs ,bucketName);
}
public String putFile(File file, String mimeType, String nameAs, String toBucket) {
try {
/**
* 上传回调策略
* 必须填写回调接口url(目前仅支持http,不支持https),可选填回调参数,回调参数请自行决定是否需要urlencode
* 若配置上传回调,则上传接口的回调将会透传回调接口的response,包括httpCode
*/
PutPolicy putPolicy = new PutPolicyForCallback.Builder("http://xxx.xxx.xxx.xxx[:port][/path]")
.addCallbackBody(new PolicyParam("key", "value"))
.build();
PutObjectResultBean response = UfileClient.object(objectAuthorization, config)
.putObject(file, mimeType)
.nameAs(nameAs)
.toBucket(toBucket)
/**
* 配置文件存储类型,分别是标准、低频、冷存,对应有效值:STANDARD | IA | ARCHIVE
*/
.withStorageType(StorageType.STANDARD)
/**
* 为云端对象配置自定义数据,每次调用将会替换之前数据。
* 所有的自定义数据总大小不能超过 8KB。
*/
// .withMetaDatas()
/**
* 为云端对象添加自定义数据,可直接调用,无须先调用withMetaDatas
* key不能为空或者""
*
*/
// .addMetaData(new Parameter<>("key","value"))
/**
* 配置上传回调策略
*/
// .withPutPolicy(putPolicy)
/**
* 是否上传校验MD5
*/
// .withVerifyMd5(false)
/**
* 指定progress callback的间隔
*/
// .withProgressConfig(ProgressConfig.callbackWithPercent(10))
/**
* 配置读写流Buffer的大小, Default = 256 KB, MIN = 4 KB, MAX = 4 MB
*/
// .setBufferSize(4 << 20)
/**
* 配置进度监听
*/
.setOnProgressListener(new OnProgressListener() {
@Override
public void onProgress(long bytesWritten, long contentLength) {
log.debug(tag, String.format("[progress] = %d%% - [%d/%d]", (int) (bytesWritten * 1.f / contentLength * 100), bytesWritten, contentLength));
}
})
.execute();
log.debug(tag, String.format("[res] = %s", (response == null ? "null" : response.toString())));
if (response != null && response.getRetCode() == 0) {
String url = UfileClient.object(objectAuthorization, config)
.getDownloadUrlFromPrivateBucket(nameAs, toBucket, expires)
.createUrl();
return url;
} else {
log.error("upload error,{}", response);
throw new RuntimeException("File Upload Error");
}
} catch (UfileClientException e) {
log.error("upload error,{}", nameAs, e);
e.printStackTrace();
throw new RuntimeException("File Upload Error");
} catch (UfileServerException e) {
log.error("upload error,{}", nameAs, e);
e.printStackTrace();
throw new RuntimeException("File Upload Error");
}
}
public void putFileAsync(File file, String mimeType, String nameAs, String toBucket) throws UfileClientException {
/**
* 上传回调策略
* 必须填写回调接口url(目前仅支持http,不支持https),可选填回调参数,回调参数请自行决定是否需要urlencode
* 若配置上传回调,则上传接口的回调将会透传回调接口的response,包括httpCode
*/
PutPolicy putPolicy = new PutPolicyForCallback.Builder("http://xxx.xxx.xxx.xxx[:port][/path]")
.addCallbackBody(new PolicyParam("key", "value"))
.build();
UfileClient.object(objectAuthorization, config)
.putObject(file, mimeType)
.nameAs(nameAs)
.toBucket(toBucket)
/**
* 配置文件存储类型,分别是标准、低频、冷存,对应有效值:STANDARD | IA | ARCHIVE
*/
.withStorageType(StorageType.STANDARD)
/**
* 为云端对象配置自定义数据,每次调用将会替换之前数据。
* 所有的自定义数据总大小不能超过 8KB。
*/
// .withMetaDatas()
/**
* 为云端对象添加自定义数据,可直接调用,无须先调用withMetaDatas
* key不能为空或者""
*
*/
// .addMetaData(new Parameter<>("key","value"))
/**
* 配置上传回调策略
*/
// .withPutPolicy(putPolicy)
/**
* 是否上传校验MD5
*/
// .withVerifyMd5(false)
/**
* 指定progress callback的间隔
*/
// .withProgressConfig(ProgressConfig.callbackWithPercent(10))
/**
* 配置读写流Buffer的大小, Default = 256 KB, MIN = 4 KB, MAX = 4 MB
*/
// .setBufferSize(4 << 20)
.executeAsync(new UfileCallback() {
@Override
public void onProgress(long bytesWritten, long contentLength) {
log.debug(tag, String.format("[progress] = %d%% - [%d/%d]", (int) (bytesWritten * 1.f / contentLength * 100), bytesWritten, contentLength));
}
@Override
public void onResponse(PutObjectResultBean response) {
log.debug(tag, String.format("[res] = %s", (response == null ? "null" : response.toString())));
}
@Override
public void onError(Request request, ApiError error, UfileErrorBean response) {
log.debug(tag, String.format("[error] = %s\n[info] = %s",
(error == null ? "null" : error.toString()),
(response == null ? "null" : response.toString())));
}
});
}
public String putStream(InputStream stream, String mimeType, String nameAs){
return putStream(stream, mimeType, nameAs ,bucketName);
}
public String putStream(InputStream stream, String mimeType, String nameAs, String toBucket) {
try {
/**
* 上传回调策略
* 必须填写回调接口url(目前仅支持http,不支持https),可选填回调参数,回调参数请自行决定是否需要urlencode
* 若配置上传回调,则上传接口的回调将会透传回调接口的response,包括httpCode
*/
PutPolicy putPolicy = new PutPolicyForCallback.Builder("http://xxx.xxx.xxx.xxx[:port][/path]")
.addCallbackBody(new PolicyParam("key", "value"))
.build();
PutObjectResultBean response = UfileClient.object(objectAuthorization, config)
.putObject(stream, mimeType)
.nameAs(nameAs)
.toBucket(toBucket)
/**
* 配置文件存储类型,分别是标准、低频、冷存,对应有效值:STANDARD | IA | ARCHIVE
*/
.withStorageType(StorageType.STANDARD)
/**
* 为云端对象配置自定义数据,每次调用将会替换之前数据。
* 所有的自定义数据总大小不能超过 8KB。
*/
// .withMetaDatas()
/**
* 为云端对象添加自定义数据,可直接调用,无须先调用withMetaDatas
* key不能为空或者""
*
*/
// .addMetaData(new Parameter<>("key","value"))
/**
* 配置上传回调策略
*/
// .withPutPolicy(putPolicy)
/**
* 是否上传校验MD5
*/
// .withVerifyMd5(false)
/**
* 指定progress callback的间隔
*/
// .withProgressConfig(ProgressConfig.callbackWithPercent(10))
/**
* 配置读写流Buffer的大小, Default = 256 KB, MIN = 4 KB, MAX = 4 MB
*/
// .setBufferSize(4 << 20)
/**
* 配置进度监听
*/
.setOnProgressListener(new OnProgressListener() {
@Override
public void onProgress(long bytesWritten, long contentLength) {
log.debug(tag, String.format("[progress] = %d%% - [%d/%d]", (int) (bytesWritten * 1.f / contentLength * 100), bytesWritten, contentLength));
}
})
.execute();
log.debug(tag, String.format("[res] = %s", (response == null ? "null" : response.toString())));
if (response != null && response.getRetCode() == 0) {
String url = UfileClient.object(objectAuthorization, config)
.getDownloadUrlFromPrivateBucket(nameAs, toBucket, expires)
.createUrl();
return url;
} else {
log.error("upload error,{}", response);
throw new RuntimeException("File Upload Error");
}
} catch (UfileClientException e) {
log.error("upload error,{}", nameAs, e);
e.printStackTrace();
throw new RuntimeException("File Upload Error");
} catch (UfileServerException e) {
log.error("upload error,{}", nameAs, e);
e.printStackTrace();
throw new RuntimeException("File Upload Error");
}
}
public void putStreamAsync(InputStream stream, String mimeType, String nameAs, String toBucket) throws UfileClientException {
/**
* 上传回调策略
* 必须填写回调接口url(目前仅支持http,不支持https),可选填回调参数,回调参数请自行决定是否需要urlencode
* 若配置上传回调,则上传接口的回调将会透传回调接口的response,包括httpCode
*/
PutPolicy putPolicy = new PutPolicyForCallback.Builder("http://xxx.xxx.xxx.xxx[:port][/path]")
.addCallbackBody(new PolicyParam("key", "value"))
.build();
UfileClient.object(objectAuthorization, config)
.putObject(stream, mimeType)
.nameAs(nameAs)
.toBucket(toBucket)
/**
* 配置文件存储类型,分别是标准、低频、冷存,对应有效值:STANDARD | IA | ARCHIVE
*/
.withStorageType(StorageType.STANDARD)
/**
* 为云端对象配置自定义数据,每次调用将会替换之前数据。
* 所有的自定义数据总大小不能超过 8KB。
*/
// .withMetaDatas()
/**
* 为云端对象添加自定义数据,可直接调用,无须先调用withMetaDatas
* key不能为空或者""
*
*/
// .addMetaData(new Parameter<>("key","value"))
/**
* 配置上传回调策略
*/
// .withPutPolicy(putPolicy)
/**
* 是否上传校验MD5
*/
// .withVerifyMd5(false)
/**
* 指定progress callback的间隔
*/
// .withProgressConfig(ProgressConfig.callbackWithPercent(10))
/**
* 配置读写流Buffer的大小, Default = 256 KB, MIN = 4 KB, MAX = 4 MB
*/
// .setBufferSize(4 << 20)
.executeAsync(new UfileCallback() {
@Override
public void onProgress(long bytesWritten, long contentLength) {
log.debug(tag, String.format("[progress] = %d%% - [%d/%d]", (int) (bytesWritten * 1.f / contentLength * 100), bytesWritten, contentLength));
}
@Override
public void onResponse(PutObjectResultBean response) {
log.debug(tag, String.format("[res] = %s", (response == null ? "null" : response.toString())));
}
@Override
public void onError(Request request, ApiError error, UfileErrorBean response) {
log.debug(tag, String.format("[error] = %s\n[info] = %s",
(error == null ? "null" : error.toString()),
(response == null ? "null" : response.toString())));
}
});
}
}
1、UFile创建存储空间域名选择私有空间和公共空间区别
私有空间目前UFile没有提供api获取在线浏览的地址(自己拼凑的地址怎么都不可以访问,因为客户端生成的url带有时间戳),只能在客户端点击获取地址。
公共空间就简单多了,直接可以得到,就是存储域名+存储地址
https://www.bilibili.com/video/BV1r4411r7au?p=54
https://blog.csdn.net/touzizhuo03/article/details/80094705
https://blog.csdn.net/han_xiaoxue/article/details/77154451
https://blog.csdn.net/qiunian144084/article/details/79972130
https://www.jianshu.com/p/dd8b52156c9f