[Azure Storage]使用Java上传文件到Storage并生成SAS签名
Azure官网提供了比较详细的文档,您可以参考:https://azure.microsoft.com/en-us/documentation/articles/storage-java-how-to-use-blob-storage/#download-a-blob
或者,请参考下面的步骤:
- 下载Azure SDK for Java,地址为:https://azure.microsoft.com/en-us/documentation/articles/java-download-azure-sdk/
- 将Azure SDK for Java的jar包导入到项目中
- 参考本文最后附加的代码
代码说明如下:
- 本人不是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/
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.EnumSet;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.TimeZone; import javax.net.ssl.*; import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.StorageCredentials;
import com.microsoft.azure.storage.StorageCredentialsAccountAndKey;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.blob.BlobContainerPermissions;
import com.microsoft.azure.storage.blob.BlobContainerPublicAccessType;
import com.microsoft.azure.storage.blob.BlockEntry;
import com.microsoft.azure.storage.blob.BlockSearchMode;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
import com.microsoft.azure.storage.blob.CloudBlockBlob;
import com.microsoft.azure.storage.blob.SharedAccessBlobPermissions;
import com.microsoft.azure.storage.blob.SharedAccessBlobPolicy; public class JavaStorageClient { static final String storageAccountName = "<Storage Account>";
static final String storageAccountKey = "<Storage Key>";
static final String containerName = "<Container Name>";
static final String videoPath = "<>";
//static final String videoPath = "D:\\Training\\all hands meeting-1.mp4"; static CloudStorageAccount storageAccount = null; private static void Init() throws InvalidKeyException, URISyntaxException, NoSuchAlgorithmException, KeyManagementException{
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){public X509Certificate[] getAcceptedIssuers(){return null;}
public void checkClientTrusted(X509Certificate[] certs, String authType){}
public void checkServerTrusted(X509Certificate[] certs, String authType){}}};
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); StorageCredentials credentials = new StorageCredentialsAccountAndKey(storageAccountName, storageAccountKey);
String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=core.Chinacloudapi.cn", storageAccountName, storageAccountKey);
storageAccount = CloudStorageAccount.parse(connectionString); } private static CloudBlobContainer GetContainer() throws URISyntaxException, StorageException{
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
CloudBlobContainer container;
container = blobClient.getContainerReference(containerName);
container.createIfNotExists(); return container;
} // For small size video, we can use this method.
private static void UploadSmallSize() throws URISyntaxException, StorageException, FileNotFoundException, IOException, InvalidKeyException{
System.out.println("===============Begin Uploading===============");
File source = new File(videoPath);
String blobName = source.getName();
CloudBlobContainer container = GetContainer();
CloudBlockBlob blob = container.getBlockBlobReference(source .getName()); blob.upload(new FileInputStream(source), source.length());
System.out.println("===============Uploading Done===============");
System.out.println("Blob URL: " + GetBlobUrl(container, blobName));
} private static void UploadLargeSize() throws URISyntaxException, StorageException, IOException, InvalidKeyException{
File source = new File(videoPath);
String blobName = source.getName();
FileInputStream inputStream = new FileInputStream(source);
final int blockLength = 1 * 1024*1024;
byte[] bufferBytes = new byte[blockLength];
int blockCount = (int)(source.length() / blockLength) + 1;
System.out.println("Total block count:"+blockCount+", Total size: "+source.length());
int currentBlockSize = 0; CloudBlobContainer container = GetContainer();
CloudBlockBlob blockBlobRef = container.getBlockBlobReference(blobName); System.out.println("===============Begin Uploading===============");
ArrayList<BlockEntry> blockList = new ArrayList<BlockEntry>(); for (int i = 0; i < blockCount; i++) {
//String blockID="OWM3MDhiMWEtODdhNS00YjE5LWE2NmEtYzAzMGJmZWIyYzli";//String.format("%09d", i);
//blockID=getBASE64(blockID);//Base64.encode(blockID.getBytes());
//String blockID="b"+String.valueOf(id);
//String blockID =Base64.encode(sid.getBytes());
//String.format("%08d", String.valueOf(10000+i));//String.valueOf(1000000+i);// Base64.encode(String.valueOf(1000000+i).getBytes());
String blockID = String.format("%08d", i);
currentBlockSize = blockLength;
if (i == blockCount - 1){
currentBlockSize = (int) (source.length() - blockLength * i);
bufferBytes = new byte[currentBlockSize];
} inputStream.read(bufferBytes, 0, currentBlockSize);
blockBlobRef.uploadBlock(blockID, getRandomDataStream(blockLength), blockLength, null, null, null);
blockList.add(new BlockEntry(blockID, BlockSearchMode.LATEST));
System.out.println("Submitted block index:" + i + ", BlockIndex:" + blockID);
}
blockBlobRef.commitBlockList(blockList);
System.out.println("===============Uploading Done==============="); System.out.println("Blob URL: " + GetBlobUrl(container, blobName));
} private static byte[] getRandomBuffer(int length) {
final Random randGenerator = new Random();
final byte[] buff = new byte[length];
randGenerator.nextBytes(buff);
return buff;
} private static ByteArrayInputStream getRandomDataStream(int length) {
return new ByteArrayInputStream(getRandomBuffer(length));
} private static String GetBlobUrl(CloudBlobContainer container, String blobName) throws StorageException, InvalidKeyException, URISyntaxException{
SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.setTime(new Date()); // Immediately applicable
policy.setSharedAccessStartTime(calendar.getTime()); // Applicable time span is 1 hour
calendar.add(Calendar.HOUR, 1);
policy.setSharedAccessExpiryTime(calendar.getTime()); // SAS grants READ access privileges
policy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.READ));
BlobContainerPermissions containerPermissions = new BlobContainerPermissions(); // Private blob-container with no access for anonymous users
containerPermissions.setPublicAccess(BlobContainerPublicAccessType.OFF);
container.uploadPermissions(containerPermissions);
String sas = container.generateSharedAccessSignature(policy,null); CloudBlockBlob blob = container.getBlockBlobReference(blobName);
String blobUri = blob.getUri().toString(); return blobUri + "?"+ sas;
} public static void main(String[] args) throws FileNotFoundException, URISyntaxException, StorageException, IOException, InvalidKeyException, KeyManagementException, NoSuchAlgorithmException {
// TODO Auto-generated method stub
Init();
//UploadLargeSize();
UploadSmallSize();
} }
[Azure Storage]使用Java上传文件到Storage并生成SAS签名的更多相关文章
- SAE上传文件到storage
还有什么比代码更清晰的讲解 html代码: 一定需要下面这个: method="post" enctype="multipart/form-data" < ...
- Java上传文件FTP服务器代码
1. 在实际的应用重,通常是通过程序来进行文件的上传. 2. 实现java上传文件到ftp服务器中 新建maven项目 添加依赖 <dependency> <groupId>c ...
- java 上传文件到 ftp 服务器
1. java 上传文件到 ftp 服务器 package com.taotao.common.utils; import java.io.File; import java.io.FileInpu ...
- java 上传文件到七牛云中
import com.alibaba.fastjson.JSONObject;import com.qiniu.common.QiniuException;import com.qiniu.commo ...
- Java 上传文件到 SFTP 抛异常 java.lang.NoClassDefFoundError: Could not initialize class sun.security.ec.SunEC 的解决办法
最近从 Op 那里报来一个问题,说是SFTP上传文件不成功.拿到的 Exception 如下: Caused by: java.lang.NoClassDefFoundError: Could not ...
- Linux下vsftpd的安装,Java上传文件实现。
首先我们需要查看是否已经安装vsftpd,输入命令 :vsftpd -v.如果出现以下信息,那么就说明已经安装vsftpd 如果没有安装,那么输入命令 : yum install vsftpd ...
- java上传文件代码
import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;impo ...
- java上传文件工具类
这个是之前整理之前所学时与使用java向邮箱发送邮件一块找到的,一起贴出来供大家参考: import java.awt.image.BufferedImage; import java.io.File ...
- java上传文件夹文件
这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...
随机推荐
- python3绘图示例4(基于matplotlib:箱线图、散点图等)
#!/usr/bin/env python# -*- coding:utf-8 -*- from matplotlib.pyplot import * x=[1,2,3,4]y=[5,4,3,2] # ...
- mysql语句的相关操作整理
事实证明,如果不经常跟代码,语句打交道,人家可是会翻脸不认人的,大脑也会觉得一脸懵逼,不知道做错了啥,这次长点记性了,把语句整理出来,不仅加强对sql语句的记忆,还能有个笔记,以后大脑懵逼了还能回来看 ...
- WSL的unable to resolve host问题
运行apt-get的时候提示 sudo: unable to resolve host DESKTOP-PS8VD9E 在 /etc/hosts文件中 127.0.0.1 对应主机名字给加一行就好了
- 静态库是.o文件的集合与弱符号
静态库是.o文件的集合. 静态库与弱符号的概念相关联. 在生成库文件时,不做强符号检查.
- Java小吐槽
简单说明,所有小吐槽都基于我的.NET经验,作为Java初学者,肯定有贻笑大方之处,欢迎之处,共同学习,共同进步. 1. The public type XXXXXXXX must be define ...
- redis set类型
- Python 爬虫的工具列表
这个列表包含与网页抓取和数据处理的Python库 网络 通用 urllib -网络库(stdlib). requests -网络库. grab - 网络库(基于pycurl). pycurl - 网络 ...
- Linux内存管理 - buddy系统
本文目的在于分析Linux内存管理机制中的伙伴系统.内核版本为2.6.31.1. 伙伴系统的概念 在系统运行过程中,经常需要分配一组连续的页,而频繁的申请和释放内存页会导致内存中散布着许多不连续的页, ...
- 不使用data-ng-app指令的表达式
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content=&q ...
- 电话状态监听 - iOS
今天接到一个监听状态的需求,当使用 App 时若电话介入需要对当前状态进行监听操作(注:并非通话内容),根据不同的状态实行相关的需求操作,废话不多说步骤如下. 首先,常规操作先引用对应的头文件,来为后 ...