Ucloud云的ufile组件使用

        ufile是Ucloud云的一个对象存储组件,可以将文件上传,下载,分片上传等很多功能,对这个技术不熟悉,第一次使用的时候踩了很多坑,写这篇博客希望能给大家带来一些帮助。

       在学习的过程中主要是参考官方给的文档和网上的一篇技术博客, 结合这篇博客和自己遇到的一些坑来给大家讲解一下。

        官方给的范例地址:https://github.com/ufilesdk-dev/ufile-javasdk 范例中官方好多名词没有进行解释,只能靠猜,感觉比较坑。

    技术博客地址:https://blog.csdn.net/qiunian144084/article/details/79972130   

1.  在maven项目中引用jar包,特别需要注意的是,这个jar包中央仓库和阿里私服都没有,需要去下载官方范例,其中有ufile-sdk这个jar包,将jar包上传到自己公司的私服,然后再在项目中引用。

  
           ufile  
           ufile-sdk  
           ${ufile_sdk.version}  
    

2.ufile.properties配置文件  名称必须是ufile.properties

ufile创建存储空间示例图:


主要配置文件

配置文件参数
bucketName:your bucketName
UCloudPublicKey=your_ucloud_public_key
UCloudPrivateKey=your_ucloud_private_key
ProxySuffix=.ufile.ucloud.cn
DownloadProxySuffix=.ufile.ucloud.cn

说明:
bucketName:上传域名的前缀 例如:weiyiyuming
UCloudPublicKey 请改成用户的公钥
UCloudPrivateKey 请改成用户的私钥
ProxySuffix 指定上传域名的后缀,可以填写源站的后缀(例如北京地域 .cn-bj.ufileos.com)或内网域名的后缀
DownloadProxySuffix 指定下载域名的后缀,可以填写源站(例如北京地域 .cn-bj.ufileos.com)或加速域名的后缀 (.ufile.ucloud.com.cn)
ufile.bucketName=your bucketName 
ufile.UCloudPublicKey=your UCloudPublicKey
ufile.UCloudPrivateKey=your UCloudPrivateKey
ufile.ProxySuffix=.cn-bj.ufileos.com
ufile.DownloadProxySuffix=.ufile.ucloud.com.cn

3.资源工具类: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);  
    }  
  
}  

4. 写ufile的工具类  那篇技术博客这里存在一个问题,他ufileUtil中设置参数使用init方法,一直没有设置配置文件中参数,当时我使用的时候一直报 empty key,在源码中找到String authorization = "UCloud " + UFileConfig.getInstance().getUcloudPublicKey() + ":" + signature;我将设置参数的这段代码放在static 静态代码块中解决这个问题。

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);  
                        }  
                    }  
                }  
            }  
        }  
    }  

}  

6.ufile创建存储空间域名选择私有空间和公共空间区别

Ucloud云的ufile组件使用_第1张图片

私有空间目前ufile没有提供api获取在线浏览的地址(自己拼凑的地址怎么都不可以访问,因为客户端生成的url带有时间戳),只能在客户端点击获取地址。

Ucloud云的ufile组件使用_第2张图片

公共空间就简单多了,直接可以得到,就是存储域名+存储地址





你可能感兴趣的:(Ucloud云的ufile组件使用)