• [Azure Storage]使用Java上传文件到Storage并生成SAS签名


    Azure官网提供了比较详细的文档,您可以参考:https://azure.microsoft.com/en-us/documentation/articles/storage-java-how-to-use-blob-storage/#download-a-blob

    或者,请参考下面的步骤:

    1. 下载Azure SDK for Java,地址为:https://azure.microsoft.com/en-us/documentation/articles/java-download-azure-sdk/
    2. 将Azure SDK for Java的jar包导入到项目中
    3. 参考本文最后附加的代码

    代码说明如下:

    • 本人不是Java方面的专家,因而代码的规范性上或许不如你专业,你可以酌情调整。此外,代码仅作测试用,请勿用于生产环境
    • 测试附件中的代码的时候,需要在代码中替换你的:存储帐号名称、存储帐号密钥、容器名称、视频路径,如下图所示:

    • 附加的代码中,提供了两个方法,UploadSmallSize和UploadLargeSize用于视频是上传。对于大文件(超过100M),需要先将文件分片而后上传。这种情况下,请使用UploadLargeSize。
    • GetBlobUrl – 这个方法是用于返回Blob的URL。由于Blob在默认情况下无法直接通过URL访问,我们在这个方法中为Blob添加了SAS签名对Blob设置了权限,使得在一定时间范围内是可以访问的。关于SAS的更多内容,您可以参考:https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-shared-access-signature-part-2/
      1 import java.io.ByteArrayInputStream;
      2 import java.io.File;
      3 import java.io.FileInputStream;
      4 import java.io.FileNotFoundException;
      5 import java.io.IOException;
      6 import java.net.URISyntaxException;
      7 import java.security.InvalidKeyException;
      8 import java.security.KeyManagementException;
      9 import java.security.NoSuchAlgorithmException;
     10 import java.security.SecureRandom;
     11 import java.security.cert.X509Certificate;
     12 import java.util.ArrayList;
     13 import java.util.Calendar;
     14 import java.util.Date;
     15 import java.util.EnumSet;
     16 import java.util.GregorianCalendar;
     17 import java.util.Random;
     18 import java.util.TimeZone;
     19 
     20 import javax.net.ssl.*;
     21 
     22 import com.microsoft.azure.storage.CloudStorageAccount;
     23 import com.microsoft.azure.storage.StorageCredentials;
     24 import com.microsoft.azure.storage.StorageCredentialsAccountAndKey;
     25 import com.microsoft.azure.storage.StorageException;
     26 import com.microsoft.azure.storage.blob.BlobContainerPermissions;
     27 import com.microsoft.azure.storage.blob.BlobContainerPublicAccessType;
     28 import com.microsoft.azure.storage.blob.BlockEntry;
     29 import com.microsoft.azure.storage.blob.BlockSearchMode;
     30 import com.microsoft.azure.storage.blob.CloudBlobClient;
     31 import com.microsoft.azure.storage.blob.CloudBlobContainer;
     32 import com.microsoft.azure.storage.blob.CloudBlockBlob;
     33 import com.microsoft.azure.storage.blob.SharedAccessBlobPermissions;
     34 import com.microsoft.azure.storage.blob.SharedAccessBlobPolicy;
     35 
     36 
     37 public class JavaStorageClient {
     38 
     39     static final String storageAccountName = "<Storage Account>";
     40     static final String storageAccountKey = "<Storage Key>";
     41     static final String containerName = "<Container Name>";
     42     static final String videoPath = "<>";
     43     //static final String videoPath = "D:\Training\all hands meeting-1.mp4";
     44     
     45     static CloudStorageAccount storageAccount = null;
     46     
     47     private static void Init() throws InvalidKeyException, URISyntaxException, NoSuchAlgorithmException, KeyManagementException{
     48         TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){public X509Certificate[] getAcceptedIssuers(){return null;}
     49         public void checkClientTrusted(X509Certificate[] certs, String authType){}
     50         public void checkServerTrusted(X509Certificate[] certs, String authType){}}};
     51         SSLContext sc = SSLContext.getInstance("TLS");
     52         sc.init(null, trustAllCerts, new SecureRandom());
     53         HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
     54 
     55         
     56         StorageCredentials credentials = new StorageCredentialsAccountAndKey(storageAccountName, storageAccountKey);
     57         String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=core.Chinacloudapi.cn", storageAccountName, storageAccountKey);
     58         storageAccount = CloudStorageAccount.parse(connectionString);
     59         
     60     }
     61     
     62     private static CloudBlobContainer GetContainer() throws URISyntaxException, StorageException{
     63         CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
     64         CloudBlobContainer container;
     65         container = blobClient.getContainerReference(containerName);
     66         container.createIfNotExists();
     67         
     68         return container;
     69     }
     70     
     71     // For small size video, we can use this method.
     72     private static void UploadSmallSize() throws URISyntaxException, StorageException, FileNotFoundException, IOException, InvalidKeyException{
     73         System.out.println("===============Begin Uploading===============");
     74         File source  = new File(videoPath);
     75         String blobName = source.getName();
     76         CloudBlobContainer container = GetContainer();
     77         CloudBlockBlob blob = container.getBlockBlobReference(source .getName());
     78         
     79         blob.upload(new FileInputStream(source), source.length());
     80         System.out.println("===============Uploading Done===============");
     81         System.out.println("Blob URL: " + GetBlobUrl(container, blobName));
     82     }
     83     
     84     
     85     private static void UploadLargeSize() throws URISyntaxException, StorageException, IOException, InvalidKeyException{
     86         File source  = new File(videoPath);
     87         String blobName = source.getName();
     88         FileInputStream inputStream = new FileInputStream(source);
     89         final int blockLength = 1 * 1024*1024;
     90         byte[] bufferBytes = new byte[blockLength];
     91         int blockCount = (int)(source.length() / blockLength) + 1;
     92         System.out.println("Total block count:"+blockCount+", Total size: "+source.length());
     93         int currentBlockSize = 0;
     94         
     95         CloudBlobContainer container = GetContainer();
     96         CloudBlockBlob blockBlobRef  = container.getBlockBlobReference(blobName);
     97         
     98         System.out.println("===============Begin Uploading===============");
     99         ArrayList<BlockEntry> blockList = new ArrayList<BlockEntry>();
    100         
    101         for (int i = 0; i < blockCount; i++) {
    102             //String blockID="OWM3MDhiMWEtODdhNS00YjE5LWE2NmEtYzAzMGJmZWIyYzli";//String.format("%09d", i);
    103             //blockID=getBASE64(blockID);//Base64.encode(blockID.getBytes());
    104             //String blockID="b"+String.valueOf(id);
    105             //String blockID =Base64.encode(sid.getBytes());
    106             //String.format("%08d", String.valueOf(10000+i));//String.valueOf(1000000+i);// Base64.encode(String.valueOf(1000000+i).getBytes());
    107            String blockID = String.format("%08d", i);
    108            currentBlockSize = blockLength;
    109            if (i == blockCount - 1){
    110                currentBlockSize = (int) (source.length() - blockLength * i);
    111                bufferBytes = new byte[currentBlockSize];
    112                }
    113            
    114            inputStream.read(bufferBytes, 0, currentBlockSize);
    115            blockBlobRef.uploadBlock(blockID, getRandomDataStream(blockLength), blockLength, null, null, null);
    116            blockList.add(new BlockEntry(blockID, BlockSearchMode.LATEST));
    117            System.out.println("Submitted block index:" + i + ", BlockIndex:" + blockID);
    118          }
    119          blockBlobRef.commitBlockList(blockList);
    120          System.out.println("===============Uploading Done===============");
    121          
    122          
    123          System.out.println("Blob URL: " + GetBlobUrl(container, blobName));
    124     }
    125     
    126     private static byte[] getRandomBuffer(int length) { 
    127         final Random randGenerator = new Random(); 
    128         final byte[] buff = new byte[length]; 
    129         randGenerator.nextBytes(buff); 
    130        return buff; 
    131     } 
    132 
    133 
    134     private static ByteArrayInputStream getRandomDataStream(int length) { 
    135         return new ByteArrayInputStream(getRandomBuffer(length)); 
    136     } 
    137 
    138     private static String GetBlobUrl(CloudBlobContainer container, String blobName) throws StorageException, InvalidKeyException, URISyntaxException{
    139         SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
    140         GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    141         calendar.setTime(new Date());
    142         
    143         // Immediately applicable
    144         policy.setSharedAccessStartTime(calendar.getTime());
    145         
    146         // Applicable time span is 1 hour
    147         calendar.add(Calendar.HOUR, 1);
    148         policy.setSharedAccessExpiryTime(calendar.getTime());
    149         
    150          // SAS grants READ access privileges
    151         policy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.READ));
    152         BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
    153         
    154         // Private blob-container with no access for anonymous users
    155         containerPermissions.setPublicAccess(BlobContainerPublicAccessType.OFF);
    156         container.uploadPermissions(containerPermissions);
    157         String sas = container.generateSharedAccessSignature(policy,null);
    158         
    159         CloudBlockBlob blob = container.getBlockBlobReference(blobName);
    160         String blobUri = blob.getUri().toString();
    161         
    162         return blobUri + "?"+ sas;
    163     }
    164     
    165     public static void main(String[] args) throws FileNotFoundException, URISyntaxException, StorageException, IOException, InvalidKeyException, KeyManagementException, NoSuchAlgorithmException {
    166         // TODO Auto-generated method stub
    167         Init();
    168         //UploadLargeSize();
    169         UploadSmallSize();
    170     }
    171 
    172 }
    View Code
  • 相关阅读:
    Android中实现定时器的三种方法 分类: Android 2015-07-14 18:04 11人阅读 评论(0) 收藏
    java构造器内部多态方法
    java继承方法覆盖
    java对象实例化 静态块,对象块,构造函数执行顺序
    Linux 的系统运行级别
    Jmeter启动jmeter-server.bat 报java.io.FileNotFoundException:rmi_keystore.jks 解决方法
    jmeter中JSON Extractors使用
    CentOS6.5下安装jenkins
    day12接口自动化测试框架
    day10 python接口开发、mock接口、网络编程
  • 原文地址:https://www.cnblogs.com/jonathanlin/p/5100029.html
Copyright © 2020-2023  润新知