![](/img/trans.png)
[英]Amazon sdk dowload large zip file from s3 bucket in spring boot java
[英]Downloading images from Amazon S3 using java spring boot
我是 AWS 开发的新手,我正在尝试从我的 Amazon S3 存储桶下载作为图像的对象。 我可以下载对象,但它们的存储方式如下图所示。
我正在使用 Spring Boot API,我的代码如下:
存储服务.java
package com.fiado.S3.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.util.IOUtils;
@Service
public class storageService {
private String bucketName = "fiadoapp";
@Autowired
private AmazonS3 s3Client;
public byte[] downloadFile(String fileName) {
try {
byte[] content;
final S3Object s3Object = s3Client.getObject(bucketName, fileName);
final S3ObjectInputStream stream = s3Object.getObjectContent();
content = IOUtils.toByteArray(stream);
s3Object.close();
return content;
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (AmazonServiceException serviceException) {
serviceException.printStackTrace();
} catch (AmazonClientException clientException) {
clientException.printStackTrace();
}
return null;
}
}
存储控制器.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fiado.S3.service.storageService;
@RestController
@RequestMapping("/file")
public class storageController {
@Autowired
private storageService service;
@GetMapping("/download/{fileName}")
public ResponseEntity<ByteArrayResource> downloadFile(@PathVariable String fileName) {
byte[] data = service.downloadFile(fileName);
ByteArrayResource resource = new ByteArrayResource(data);
return ResponseEntity
.ok()
.contentLength(data.length)
.header("Content-type","application/octet-stream")
.header("content-disposition","attachment; filename=\"" + fileName + "\"")
.header("Cache-Control", "no-cache")
.body(resource);
}
}
谁能告诉我如何将我的文件下载为图像?
请参阅此 AWS 教程。 它讨论了这个确切的用例,并向您展示了如何使用 Spring BOOT 应用程序将位于 Amazon S3 存储桶中的图像下载到您的 Web 浏览器。 例如,此图像显示下载名为Lake.png的图像。
此应用程序使用适用于 Java V2 的 AWS 开发工具包。 看:
创建使用 AWS SDK for Java 分析照片的动态 Web 应用程序
此示例使用同步 Java 客户端。 如果您更喜欢使用 Java 异步客户端,请参阅:
我测试了这段代码,从 S3 下载图像效果很好。
唯一的区别是,你能交叉检查你的供应方式吗
文档名称
路径变量 ?
另外,您是否尝试过使用独立程序下载文件? 只是为了排除是
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.