spring boot怎么从oss上下载文件?
时间: 2023-06-18 17:05:27 浏览: 204
使用Java SDK for Aliyun OSS(https://help.aliyun.com/document_detail/32008.html)和Spring的RestTemplate(https://spring.io/guides/gs/consuming-rest/)可以实现从OSS上下载文件。
以下是一个示例:
```java
@Autowired
private OSS ossClient;
@Autowired
private RestTemplate restTemplate;
public void downloadFileFromOSS(String bucketName, String objectName, String localFilePath) throws IOException {
OSSObject ossObject = ossClient.getObject(bucketName, objectName);
InputStream inputStream = ossObject.getObjectContent();
OutputStream outputStream = new FileOutputStream(localFilePath);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
```
其中,`ossClient`是通过`OSSClientBuilder`构造的阿里云OSS客户端实例,`bucketName`是OSS中存储文件的桶的名称,`objectName`是要下载的文件的名称,`localFilePath`是下载到本地的文件路径。
使用`RestTemplate`可以实现从OSS上下载文件并返回一个字节数组的示例:
```java
public byte[] downloadFileFromOSS(String bucketName, String objectName) throws IOException {
String url = ossClient.generatePresignedUrl(bucketName, objectName, new Date(System.currentTimeMillis() + 3600 * 1000)).toString();
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class);
return response.getBody();
}
```
其中,`generatePresignedUrl`方法生成一个带有签名的URL,`url`即为可用于下载文件的URL。使用`RestTemplate`向该URL发送GET请求可以获取文件的字节数组。
阅读全文