我在S3存储桶中有一个包含json文件的文件夹。我使用的是Spring Boot。用户提供folder name和特定文件(json file)名称。
public ResponseEntity<?> downloading(String folderName, String fileName) throws IOException {
S3Object s3Object = s3client
.getObject(new GetObjectRequest(s3BucketName, folderName + fileName));
if (s3Object.getKey().length() > 0) {
//enables the user to dowload json file
//return the object that can be dowloaded, status code
return new ResponseEntity<>( HttpStatus.OK);
}
else{
//return error message and status code
return new ResponseEntity<>( HttpStatus.NOT_FOUND);
}
}发布于 2019-09-05 00:45:33
我已经参考了here的答案。
因此,我只添加了对您有帮助的代码的一部分:
public ResponseEntity<byte[]> downloading(String folderName, String fileName) {
S3Object s3Object = s3client
.getObject(new GetObjectRequest(s3BucketName, folderName + fileName));
if (s3Object.getKey().length() > 0) {
S3ObjectInputStream input = s3Object.getObjectContent();
byte[] bytes = IOUtils.toByteArray(input);
String file = URLEncoder.encode(s3Object.getKey(), "UTF-8").replaceAll("\\+", "%20");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentLength(bytes.length);
headers.setContentDispositionFormData("attachment", file);
return new ResponseEntity<byte[]>(bytes, HttpStatus.OK);
}
return new ResponseEntity<byte[]>(null, HttpStatus.NOT_FOUND);
}谢谢。:)
https://stackoverflow.com/questions/57792357
复制相似问题