java 获取文件下载链接
时间: 2023-10-20 07:59:53 浏览: 91
Java 中获取文件下载链接的方法,一般需要先了解文件存储的情况,比如文件存储在本地还是存储在云存储服务中等。下面以常见的云存储服务举例说明。
1. Amazon S3
```java
AmazonS3 s3Client = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey));
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectKey);
URL url = s3Client.generatePresignedUrl(request);
String downloadUrl = url.toString();
```
2. Google Cloud Storage
```java
Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
Blob blob = storage.get(bucketName, objectKey);
String downloadUrl = blob.signUrl(1, TimeUnit.DAYS).toString();
```
3. Microsoft Azure Blob Storage
```java
String connectionString = "DefaultEndpointsProtocol=https;AccountName=<account-name>;AccountKey=<account-key>;EndpointSuffix=core.windows.net";
String containerName = "<container-name>";
String blobName = "<blob-name>";
CloudStorageAccount account = CloudStorageAccount.parse(connectionString);
CloudBlobClient serviceClient = account.createCloudBlobClient();
CloudBlobContainer container = serviceClient.getContainerReference(containerName);
CloudBlockBlob blob = container.getBlockBlobReference(blobName);
String downloadUrl = blob.getUri().toString() + blob.generateSharedAccessSignature(policy, null);
```
4. Alibaba Cloud Object Storage Service
```java
String endpoint = "<endpoint>";
String accessKeyId = "<access-key-id>";
String accessKeySecret = "<access-key-secret>";
String bucketName = "<bucket-name>";
String objectKey = "<object-key>";
String downloadUrl = "https://" + bucketName + "." + endpoint + "/" + objectKey + "?Expires=1800&OSSAccessKeyId=" + accessKeyId + "&Signature=" + URLEncoder.encode(OSSUtils.generateAuthorization(accessKeyId, accessKeySecret, "GET", null, null, bucketName, objectKey, 1800), "UTF-8");
```
其中,`accessKey` 和 `secretKey` 分别是云存储服务的访问凭证,`bucketName` 和 `objectKey` 分别
阅读全文